【问题标题】:R GGPLOT2 Multiple Lines with same Y axisR GGPLOT2 具有相同 Y 轴的多条线
【发布时间】:2017-07-31 03:24:40
【问题描述】:

我一直在 r 中与 ggplot 作斗争。我正在尝试创建一个线图,其中绘制了三个变量 - 小树苗、中树苗和大树苗。 X 轴是“平均树苗数量”,Y 轴应该是“鸟类物种丰富度”。

这是摘录:

birdspp smallsaplings   mediumsaplings  largesaplings
95      5.044642857     2.384615385     1.30952381
97      3.482269504     1.873684211     1.390625
63      6.285714286     2               2.4
57      5.216216216     1.666666667     1.125

我的问题是,我这辈子都不知道如何在一张图上绘制所有三条线!

我尝试了两种方法。传统的充满希望的方式...

 ggplot(data, aes(y=birdspp, x=saplings)) + 
  geom_line(aes(x = smallsaplings, colour = "blue"))+
  geom_point(aes(x = smallsaplings, colour = "blue")) + 
  geom_line(aes(x = mediumsaplings, colour = "green")) +
  geom_point(aes(x = mediumsaplings, colour = "green")) + 
  geom_line(aes(x = largesaplings, colour = "red")) +
  geom_point(aes(x = largesaplings, colour = "red")) 

which produces this monstrosity :(

并使用 reshape 库中的 melt 函数...

mdf <- melt(mdf, id.vars="Sapplings", value.name="value", variable.name="birdspp")
ggplot(data=mdf, aes(x=Sapplings, y=value, group = birdspp, colour = birdspp)) +
    geom_line() +
    geom_point( size=4, shape=21, fill="white")

抱歉,如果错误非常明显,我是新手。

【问题讨论】:

  • 一个问题是 x=saplings 在您对 ggplot 的主要调用中。您的数据中不存在此列。如果将数据转换为“长”格式,绘图也会容易得多。像这样的东西:library(reshape2); ggplot(melt(data, id.var="birdspp"), aes(x=value, y=birdspp, colour=variable)) + geom_line() + geom_point().
  • 使用你原来的方法,每条线都可以绘制成类似这样:ggplot(data, aes(y=birdspp)) + geom_line(aes(x=smallsaplings), colour="blue")
  • 我快接近了!图表在这里,我只是在努力寻找最佳拟合线。 geom_line 只是连接所有点,理想情况下我想要 geom_abline 但它似乎不起作用。
  • geom_smooth(method="lm")

标签: r ggplot2 reshape


【解决方案1】:

这是一个经典的“从宽到长”的问题。如果你先整理数据会更容易,所以它有一列是树苗类型,另一列是平均数。

library(dplyr)
library(tidyr)

df1 %>% 
  gather(sapling_type, mean_number, -birdspp)

现在您可以通过管道将其输入ggpplot 并按树苗类型着色。不过,我不确定线条。也许先从点开始。

df1 %>% 
  gather(sapling_type, mean_number, -birdspp) %>% 
  ggplot(aes(mean_number, birdspp)) + geom_point(aes(color = sapling_type))

结果:

【讨论】:

  • 谢谢!太好了,我现在有图表,只是在最适合的线中挣扎。 Geom_line 或 geom_abline 不适合这个。如果我弄明白了会告诉你的!
  • 你想要每组一条线(树苗类型)还是一条穿过所有点的线?
  • 每个树苗类型。这个背后的生物学只是表明树苗不会改变支离破碎的森林中的物种丰富度。很有趣的东西。如果您有兴趣,它们似乎更受树木周长(森林年龄)的影响!
  • 您可以在ggplot2 中拟合和绘制线性模型。尝试将此添加到答案中第二个代码示例的末尾:+ geom_smooth(aes(group = sapling_type, color = sapling_type), method = "lm")
  • 恐怕没有这样的运气