1

使用数据框 d 中的变量(日、月、计数),我使用下面的 ggplot:

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 轴上正确显示天数?

4

1 回答 1

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

在此处输入图像描述

于 2013-05-09T05:19:58.907 回答