r - 使用构面时如何在 ggplot 中标记 x 轴

标签 r ggplot2

我试图用下面的代码更改绘图上的 x 轴。我按照与图右侧图例相对应的顺序在scale_x-discrete上命名了所需的标签,但它们最终变得困惑。 《三年》中 Jade 米出现了两次而燕麦缺失,而《四年》中 Jade 米又出现了两次而苜蓿缺失了。 “三年”和“四年”的标签也混淆了。

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

谢谢!

最佳答案

您可以使用 plyr 包中的 mapvaluesRot.Herb 值映射到轴标签,而不是 scale_x_discrete然后对此进行分组。我不确定我的标签是否完全正确,但大致上是这样的

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

关于r - 使用构面时如何在 ggplot 中标记 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28864704/

相关文章:

r - 计算 R 中多列的唯一值

r - 在具有季节性周期的时间序列中插入缺失值

r - ggplot 2 带有发散调色板的条形图

r - Log10 x 轴在顶部和 y 轴 geom_line

r - 使用 rowwise() 计算数据帧每一行中 NA 的数量的问题

r - 制作堆叠矩形而不是列的直方图

r - 为什么空逻辑向量通过 stopifnot() 检查?

r - 在ggplot2中,如何选择图例中出现哪个几何图形?

r - 向每个方面添加不同的 geom_segment

r - 取消列出列名称并在facet_grid中使用它