ggplot multi-factor-level grouping for boxplot with continuous scale

不问归期 提交于 2019-12-12 21:26:59

问题


I'm trying to create a boxplot of the following data

Temp<-rnorm(90,mean=100,sd=10)
Yr<-sample(c("1999","2000","2005","2009","2010"),size=90,replace=TRUE)
Month<-sample(c("June","July","August"),size=90,replace=TRUE)
Month
df<-data.frame(Temp,Month,Yr)

The visual I want and its corresponding code are below:

ggplot(df,aes(x=interaction(Month,Yr),y=Temp,fill=Month))+
    geom_boxplot()+
    xlab("Year")+
    ylab("Daily Maximum Temperature")

You'll notice, though, that there are a few years missing from the data, and I'm trying to make the plot reflect that with gaps in the x-scale. The other problem is the text and tick marks on the axis. I'd like the ticks to just be the Year of observation rather than Month.Year since the month is already coded in the fill. I've tried scale_x_discrete, but trying to supply discrete values for a continuous axis spits out a blank graph and an error. I've met my swearing at the computer quota for the day, and it would be really awesome to get a little help on this.


回答1:


This creates huge gaps, as every year gets its own gap, but you can adapt this by passing only specific years as the levels argument to the factor() call.

df$Yr <- factor(df$Yr, levels=1999:2010)

ggplot(df,aes(x=Yr,y=Temp,fill=Month))+
  geom_boxplot(position=position_dodge(1))+
  ylab("Daily Maximum Temperature") +
  scale_x_discrete("Year", drop=FALSE)


来源:https://stackoverflow.com/questions/31999185/ggplot-multi-factor-level-grouping-for-boxplot-with-continuous-scale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!