gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:06:32 26 4
gpt4 key购买 nike

我试图用下面的代码更改绘图上的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com