[英]How to plot different y with the same x in ggplot?
Let's say I have a dataframe with one column x and other variables y1, y2, ... all continuos.假设我有一个数据框,其中包含一列 x 和其他变量 y1, y2, ... 全部连续。
What's the quickest way to plot x ~ y1 and y2 on two different graphs but like they were in facet_wrap?在两个不同的图上绘制 x ~ y1 和 y2 的最快方法是什么,但就像它们在 facet_wrap 中一样?
I know I can build multiple ggplots and use grid.arrange (but this way I am pasting the same code over and over for each y with no changes but the index of y) but is it possible to do it with facets?我知道我可以构建多个 ggplots 并使用 grid.arrange (但这样我会一遍又一遍地为每个 y 粘贴相同的代码,除了 y 的索引外没有任何变化)但是是否可以使用 facet 来做到这一点?
Seems rather simple but I am having trouble with facets.看起来很简单,但我在方面遇到了麻烦。
This type of problems generaly has to do with reshaping the data.这类问题通常与重塑数据有关。 The format should be the long format and the data is in wide format.格式应该是长格式,数据是宽格式。
I will use the first 3 columns of built in dataset iris
as an example dataset.我将使用内置数据集iris
的前 3 列作为示例数据集。
library(ggplot2)
df1 <- iris[1:3]
names(df1) <- c("x", "y1", "y2")
df1_long <- reshape2::melt(df1, id.vars = "x")
head(df1_long)
ggplot(df1_long, aes(x, value, colour = variable)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
facet_grid(rows = vars(variable))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.