【问题标题】:Can the x-axis labels be ordered when using a combined bar & line graph in R?在 R 中使用组合条形图和折线图时可以对 x 轴标签进行排序吗?
【发布时间】:2013-05-09 03:21:51
【问题描述】:

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

【问题讨论】:

    标签: r ggplot2 axis-labels


    【解决方案1】:

    您可以使用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))
    

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      相关资源
      最近更新 更多