Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change x-axis breaks ggplot2

Tags:

r

ggplot2

I'm trying to make the x-axis the actual years instead of ggplot2 break them up into halves. How would I set the specific x-axis to the years?

dput:

df <- structure(list(year = c(1930, 1931, 1932, 1933, 1934, 1935, 1936, 
1937, 1938, 1939, 1940), ppt = c(59.0033808749924, 64.5812917950552, 
66.5926177672304, 59.4756152030825, 54.7584384173037, 73.2530022881949, 
52.152143860761, 62.667460409034, 68.3809388906197, 57.8704092161023, 
62.8957857266413), anom = c(0.820287105396386, 0.897833312663238, 
0.925795519832683, 0.826852283938926, 0.761272325064239, 1.01839068062701, 
0.725038641741477, 0.871226511754963, 0.950657430049865, 0.804536108948638, 
0.874400775857991)), row.names = c(NA, -11L), class = c("tbl_df", 
"tbl", "data.frame"), .Names = c("year", "ppt", "anom"))

Code:

qplot(year, anom, data = df, geom="smooth", main = "Precipitaion ", ylab = "Anomaly", xlab = "", scale_x_continuous(breaks=seq(1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940), labels = c("1930", "1931", "1932", "1933", "1934", "1935", "1936", "1937", "1938", "1939", "1940")))

Output:

enter image description here

like image 573
Vedda Avatar asked Oct 17 '15 21:10

Vedda


People also ask

How do I change the x-axis values in ggplot2?

You can use the scale_x_discrete() function to change the x-axis labels on a plot in ggplot2: p + scale_x_discrete(labels=c('label1', 'label2', 'label3', ...))

How do you add a break to the x-axis in R?

To add axis breaks in ggplot2 plots in R, we use scale_x_break() and scale_y_break() functions. These functions take a vector as a parameter that has breakpoints.

How do I change the x-axis in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do you change X and Y labels in ggplot2?

To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .


1 Answers

This code should work,

grp = ggplot(df,aes(x=year,y=anom)) +
      geom_smooth() +
      labs(title="Precipitaion", y="Anomaly", x = "")
grp + scale_x_continuous(breaks=seq(1930, 1940, 1))

also the syntax for seq is seq(start,end,step-by).

enter image description here

like image 167
Pankil Shah Avatar answered Sep 21 '22 13:09

Pankil Shah