gpt4 book ai didi

r - 如何为面添加不同的线

转载 作者:行者123 更新时间:2023-12-03 07:26:35 25 4
gpt4 key购买 nike

我有一些数据,可以观察两种不同物种的单一培养和混合培养之间的生长差异。此外,我还制作了一个图表来使我的数据更清晰。

我想要一个带有误差线的条形图,整个数据集当然更大,但对于这个图来说,这是带有条形图平均值的data.frame

plant           species     means
Mixed culture Elytrigia 0.886625
Monoculture Elytrigia 1.022667
Monoculture Festuca 0.314375
Mixed culture Festuca 0.078125

利用这些数据,我在 ggplot2 中制作了一个图表,其中 plant 位于 x 轴,means 位于 y 轴,我用一个方面来划分物种。

这是我的代码:

    limits <- aes(ymax = meansS$means + eS$se, ymin=meansS$means - eS$se)
dodge <- position_dodge(width=0.9)

myplot <- ggplot(data=meansS, aes(x=plant, y=means, fill=plant)) + facet_grid(. ~ species)
myplot <- myplot + geom_bar(position=dodge) + geom_errorbar(limits, position=dodge, width=0.25)
myplot <- myplot + scale_fill_manual(values=c("#6495ED","#FF7F50"))
myplot <- myplot + labs(x = "Plant treatment", y = "Shoot biomass (gr)")
myplot <- myplot + opts(title="Plant competition")
myplot <- myplot + opts(legend.position = "none")
myplot <- myplot + opts(panel.grid.minor=theme_blank(), panel.grid.major=theme_blank())

到目前为止一切都很好。但是,我想在两个面上添加两条不同的水平线。为此,我使用了以下代码:

    hline.data <- data.frame(z = c(0.511,0.157), species = c("Elytrigia","Festuca")) 
myplot <- myplot + geom_hline(aes(yintercept = z), hline.data)

但是,如果我这样做,我会得到一个图,其中有两个额外的面,其中绘制了两条水平线。相反,我希望将水平线绘制在带有条的面上,而不是创建两个新的面。任何人都知道如何解决这个问题。

我认为如果我把现在创建的图表放在上面会更清楚:

enter image description here

最佳答案

确保两个数据集中的变量物种相同。如果它是其中一个因素,那么它也一定是另一个因素

library(ggplot2)
dummy1 <- expand.grid(X = factor(c("A", "B")), Y = rnorm(10))
dummy1$D <- rnorm(nrow(dummy1))
dummy2 <- data.frame(X = c("A", "B"), Z = c(1, 0))
ggplot(dummy1, aes(x = D, y = Y)) + geom_point() + facet_grid(~X) +
geom_hline(data = dummy2, aes(yintercept = Z))

enter image description here

dummy2$X <- factor(dummy2$X)
ggplot(dummy1, aes(x = D, y = Y)) + geom_point() + facet_grid(~X) +
geom_hline(data = dummy2, aes(yintercept = Z))

enter image description here

关于r - 如何为面添加不同的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11846295/

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