在ggplot,R中安排每月时间序列的标签

时间:2018-04-04 16:04:28

标签: r ggplot2

我有一个非常大的dataframe,从1985年至今的五月到九月的观察结果就像这样的例子:

month<-c("May","June","July","August","September","May","June","July","August","September")
 year<-c("1985","1985","1985","1985","1985","1986","1986","1986","1986","1986")
 value<-c(2,6,4,5,9,7,2,6,5,4)
 df<-data.frame(month,year,value)

当我尝试绘制按年份分组的数据时,月份的顺序会发生变化。我试图订购数据并将月份列设置为一个因素,但仍然得到以下结果。

ggplot(df, aes(x=month, y=value,group=year))+theme_bw()+theme(plot.background = element_blank(),panel.grid.major = element_blank()
                                                           ,panel.grid.minor = element_blank()) +ylim(0,10)+labs(x="Month",y=expression(bold(paste("variable here"))))+
    theme(axis.title.x = element_text(face="bold", size=12),axis.text.x = element_text(size=9))+
    theme(axis.title.y = element_text(face="bold", size=12),axis.text.y = element_text(size=9))+theme(axis.text.x = element_text(angle = 45, hjust = 1))+
    geom_line(linetype="solid", size=1)+geom_point(color="gray7", size=2,shape=15)

任何想法如何解决这个问题?我想保留我的专栏(5月,6月,7月,8月,9月)的顺序

由于

1 个答案:

答案 0 :(得分:1)

month设置为一个因子并指定级别的顺序(使用参数levels)可以解决问题,如下所示。

month<-c("May","June","July","August","September","May","June","July","August","September")
    year<-c("1985","1985","1985","1985","1985","1986","1986","1986","1986","1986")

value<-c(2,6,4,5,9,7,2,6,5,4)

df<-data.frame(month,year,value)

df$month <- factor(df$month, levels = c("May", "June", "July", "August", "September"))

ggplot(df, aes(x=month, y=value,group=year))+theme_bw()+theme(plot.background = element_blank(),panel.grid.major = element_blank()
                                  ,panel.grid.minor = element_blank()) +ylim(0,10)+labs(x="Month",y=expression(bold(paste("variable here"))))+
    theme(axis.title.x = element_text(face="bold", size=12),axis.text.x = element_text(size=9))+
    theme(axis.title.y = element_text(face="bold", size=12),axis.text.y = element_text(size=9))+theme(axis.text.x = element_text(angle = 45, hjust = 1))+
    geom_line(linetype="solid", size=1)+geom_point(color="gray7", size=2,shape=15)