2013-05-09 64 views
1

使用在數據幀d中的變量(日,月,計數),我使用ggplot下面:在R中使用組合條形圖和折線圖時,是否可以對x軸標籤進行排序?

day <- c("Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week","Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week") 
day <- factor(day, level=c("Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week")) 
month<-c("Jan","Jan","Jan","Jan","Jan","Jan","Jan","Jan","Feb","Feb","Feb","Feb","Feb","Feb","Feb","Feb") 
month<-factor(month,level=c("Jan","Feb")) 
count <- c(4,5,6,8,3,4,9,5.57,2,4,3,7,1,9,3,4.14) 
d <- data.frame(day=day,count=count,month=month) 
d 

線圖以下正確地定購天:

ggplot()+geom_line(data=d[d$day!="Week",],aes(x=day, y=count, group=month, colour=month)) 

下條形圖正確地顯示兩個計數:

ggplot()+geom_bar(data=d[d$day=="Week",],aes(x=day, y=count, fill=month),position="dodge") 

然而,天的順序是在組合的圖形不正確的:

ggplot()+geom_line(data=d[d$day!="Week",],aes(x=day, y=count, group=month, colour=month))+geom_bar(data=d[d$day=="Week",],aes(x=day, y=count, fill=month),position="dodge") 

如何在x軸上正確顯示天數的順序?

回答

3

您可以使用scale_x_discrete()以參數limits=更改休息順序。由於您的原始數據框因子水平是正確的,所以您可以使用limits=levels(d$day)

ggplot()+ 
    geom_line(data=d[d$day!="Week",], 
        aes(x=day, y=count, group=month, colour=month))+ 
    geom_bar(data=d[d$day=="Week",], 
        aes(x=day, y=count, fill=month),position="dodge")+ 
    scale_x_discrete(limits=levels(d$day)) 

enter image description here

相關問題