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

标签 r ggplot2 facet

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

我想要一个带有误差线的条形图,整个数据集当然更大,但对于这个图来说,这是带有条形图平均值的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/

相关文章:

使用 ggplot2 根据填充值对堆叠的条形图 x 重新排序

python - 更改 seaborn 面网格中的线条样式

jsf - 为什么复合组件中某个方面内的 commandLink 会呈现错误?

r - drake - 映射 ggplot 目标以输出它们

r - 如何修改由 scales 包生成的标签?

重新排序 data.table 行,以便没有两个连续的行是相同的

R:Selenium 服务器信号端口 = 4567 已在使用中

r - 根据R中字符串中不同位置的不同条件进行过滤

r - data.table对象分配了:= from within function not printed

r - 在 ggplot2 中跨时间绘制多个组的平均值