【问题标题】:How to use ggplot to create facets with two factors?如何使用 ggplot 创建具有两个因素的构面?
【发布时间】:2019-02-13 23:58:15
【问题描述】:

我正在尝试使用以前模型中的一些数据绘制带有构面的图。举个简单的例子:

t=1:10;
x1=t^2;
x2=sqrt(t);
y1=sin(t);
y2=cos(t);

我如何在 2x2 网格中绘制这些数据,作为行一个因素(水平 xy,用不同颜色绘制)和列另一个因素(水平 12,绘制线型不同)?

注意:t 是所有子图 X 轴的公共变量。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

如果可以先将数据放入tidy form,ggplot 会更有帮助。 df 是您的数据,df_tidy 是整齐形式的数据,其中系列在一个列中标识,可以映射到 ggplot 中——在本例中为构面。

library(tidyverse)
df <- tibble(
  t=1:10,
  x1=t^2,
  x2=sqrt(t),
  y1=sin(t),
  y2=cos(t),
)

df_tidy <- df %>%
  gather(series, value, -t)

ggplot(df_tidy, aes(t, value)) + 
  geom_line() +
  facet_wrap(~series, scales = "free_y")

【讨论】:

  • 非常感谢您的回答!这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
  • 2019-01-30
  • 2018-11-18
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
  • 2013-01-16
相关资源
最近更新 更多