2016-04-04 54 views
0

我正試圖用ggplot2生成barplot。我想出了一個問題,即我的圖的邊界正在向右移動,即使x軸的極限由scale_x_discrete設置。我怎樣才能限制圖表框架以12月的欄結束?限制ggplot2中的barplot的框架

下面是代碼:

mean<-c(36.7, 17.3, 25.6, 41.5, 135.9, 203.9, 289.5, 277.8, 163.2, 67.4, 45, 44) 
month<-c(1,2,3,4,5,6,7,8,9,10,11,12) 
mean_CH<-data.frame(month, mean) 


p<-ggplot(data=mean_CH, aes(x=month, y=mean)) + geom_bar(stat="identity", fill="light blue") + 
    ylab(expression(atop(paste("XXX "),paste("(XX"," ", XX^-1, " ", X^-1, " ", XX^-1,")", sep=""))))+ 
    scale_x_discrete(breaks=c("1","2","3","4","5","6","7","8","9","10","11", "12"), 
    labels=c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))+ 
    ggtitle("XXX")+ 
    theme_bw() 

這裏是我的結果: enter image description here

+1

在'aes()'裏面試試'x = factor(month)'。 – mtoto

+0

工作!非常感謝這個非常快速的解決方案!你可以添加這個答案! – xmisx

+1

順便說一下,您可以使用'breaks = as.character(1:12)'和'labels = month.abb'。 – Axeman

回答

2

在你的數據,month仍然是一個數值變量,這會導致偏差,因爲scale_x_discrete()定義上預計離散值x軸。我們可以通過在aes()內分解month來解決此問題。

ggplot(data = mean_CH, aes(x = factor(month), y = mean)) + ...