【发布时间】: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")