2015-10-17 216 views
1

我想讓x軸的實際年代代替ggplot2將它們分成兩半。我如何將特定的x軸設置爲幾年?更改x軸中斷ggplot2

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")) 

代碼:

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"))) 

輸出:

enter image description here

+0

選項1:使它們成爲因子;選項2:讓他們成爲角色;選項3:將它們轉換爲實際的日期。 – hrbrmstr

+0

因爲year是數字,所以可以像這樣設置中斷:'ggplot(df,aes(year,anom))+ geom_smooth()+ scale_x_continuous(breaks = seq(1930,1940,2))''。我將主要間隔設置爲2,但您當然可以將其設置爲任何您喜歡的。 – eipi10

回答

2

此代碼應該工作,

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)) 

seq的語法也是seq(start,end,step-by)

enter image description here

+0

這工作。謝謝! – Vedda