如何在ggplot中用相同的x绘制不同的y? [英] How to plot different y with the same x in ggplot?

查看:47
本文介绍了如何在ggplot中用相同的x绘制不同的y?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个数据框,其中包含一列x和其他变量y1,y2,...都是连续的.

在两个不同的图上绘制x〜y1和y2的最快方法是什么,就像它们在facet_wrap中一样?

我知道我可以构建多个ggplots并使用grid.arrange(但是通过这种方式,我可以为每个y重复粘贴相同的代码,而无需更改,但y的索引),但是可以通过构面来做到这一点吗?

看起来很简单,但是我在构面方面遇到麻烦.

解决方案

这种类型的问题通常与重塑数据有关.格式应为

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

这篇关于如何在ggplot中用相同的x绘制不同的y?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆