首页 > 解决方案 > How to plot multiple graphs into one using ggplot?

问题描述

How can i plot multiple line graphs into one? I have four separate datasets which all have the same x-axis (it is like time, i.e. all in order).

So the dataset looks like this

x        y1    y2    y3    y4
12350  0.032  0.283 0.043  0.012
13200  0.234  0.229 0.934  0.002
15504  0.001  0.510 0.394. 0.294
17709  0.923  0.394 0.022  0.202
.
.
.

The problem is, what do I enter in ggplot? I can plot individual plots fine but not sure how to combine them. Adding the two plots below does not work, maybe I'm missing something really obvious...

ggplot(df, aes(x=x, y=y1)) + geom_line()
ggplot(df, aes(x=x, y=y2)) + geom_line()

标签: rggplot2

解决方案


听起来你想要一个有四条曲线的图。您可以使用任意数量的转换函数将数据框从宽转换为长。基本上,您希望得到一个包含三列的数据框,一列用于 x 值,一列用于 y 值,另一列带有一个标识符,该标识符显示原始 y 中的哪一个与每个 x,y 对相关联。

x     y     id
12350 0.032 y1
12350 0.028 y2
12350 0.043 y3
12350 0.012 y2
13200 0.234 y1
etc.

然后使用 id group 美学来单独绘制曲线。如果你搜索“从宽到长”,你会得到很多关于如何进行转换的建议。


推荐阅读