简体   繁体   中英

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.

What's the quickest way to plot x ~ y1 and y2 on two different graphs but like they were in 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?

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.

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))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM