如何在使用facet时在ggplot中标记x轴

时间:2015-03-04 20:52:45

标签: r ggplot2

我试图使用下面的代码更改我的绘图上的x轴。我在scale_x-discrete上命名了所需的标签,其顺序与图表右侧的图例相对应,但它们最终变得混乱。玉米出现两次,而燕麦缺少“三年”,然后玉米出现两次“四年”,紫花苜蓿失踪。标签混合了“三年”和“四年”。

data$rotation[data$Rot.trt %in% c("C2", "S2")]<-"TwoYear"
data$rotation[data$Rot.trt %in% c("C3", "S3", "O3")]<-"ThreeYear"
data$rotation[data$Rot.trt %in% c("C4", "S4", "O4", "A4")]<-"FourYear"

##plot, by rotation #scales = free_x X axis depends on facet
data$rotation <- factor(data$rotation, levels = c("TwoYear", "ThreeYear", "FourYear"))
ggplot(data, aes(Rot.Herb, kg.ha, fill=Crop))+
  geom_boxplot()+
  facet_grid(~rotation, scales = "free_x", space="free_x")+
  scale_fill_brewer(palette = "Paired")+
  ggtitle("Weed biomass by plot")+
  theme(plot.title = element_text(size=30, face="bold", vjust=2))+
  xlab("Rotation systems and Herbicide regimes (L = Low herbicide regime, C = Conventional herbicide regime)")+
  scale_x_discrete(labels = c("Corn C", "Corn L", "Soybean C", "Soybean L", "Corn C", "Corn L", "Oat C", "Oat L", "Soybean C", "Soybean L", "Alfalfa C", "Alfalfa L", "Corn C", "Corn L", "Oat C", "Oat L", "Soybean C", "Soybean L"))+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))+
  ylab("Weed dry weight")

请在此处查找图片和数据:

https://www.dropbox.com/sh/jb6gjznyw2q16mx/AADcNKiicqkoHxpFYIsaTgk9a?dl=0

enter image description here

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用scale_x_discrete包中的Rot.Herbmapvalues值映射到轴标签,而不是plyr,然后将其分组。我不确定我是否完全正确地使用了标签,但是我还不确定这些标签

...
library(plyr)
data$Rot.Herb.label <- mapvalues(data$Rot.Herb, 
          c('C2conv', 'C2low', 'S2conv', 'S2low', 'C3conv', 'C3low',
            'O3conv', 'O3low', 'S3conv', 'S3low', 'A4conv', 'A4low',
            'C4conv', 'C4low', 'O4conv', 'O4low', 'S4conv', 'S4low'),
          c("Corn C", "Corn L", "Soybean C", "Soybean L", 
            "Corn C", "Corn L", "Oat C", "Oat L", "Soybean C", 
            "Soybean L", "Alfalfa C", "Alfalfa L", "Corn C", "Corn L",
            "Oat C", "Oat L", "Soybean C", "Soybean L"))


ggplot(data, aes(Rot.Herb.label, kg.ha, fill=Crop))+
  geom_boxplot()+
  facet_grid(~rotation, scales = "free_x", space="free_x")+
  scale_fill_brewer(palette = "Paired")+
  ggtitle("Weed biomass by plot")+
  theme(plot.title = element_text(size=30, face="bold", vjust=2))+
  xlab("Rotation systems and Herbicide regimes (L = Low herbicide regime, C = Conventional herbicide regime)")+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))+
  ylab("Weed dry weight")
...

那产生了 enter image description here