【问题标题】:Create a grouped plot by more than one factor按多个因素创建分组图
【发布时间】:2018-01-17 13:36:26
【问题描述】:

我目前正在研究dplyrggplot 的优势。在我的一个情节中,我有一个data.frame,其中包含两个因素,即F1F2。我想为F1F2(笛卡尔积,这里是4=2 x 2 结果)的每个可能组合创建一个线图。

似乎ggplot 在这里只接受一个因素F1。这样我的情节中的线条是连接的,而我希望有四条单独的线条。

library(dplyr)
library(ggplot2)

df<-data.frame("X"=c(1,2,4,5,7,8,10,11),"Y"=c(1,2,3,4,5,6,7,8),"F1"=c(1,1,1,1,2,2,2,2),"F2"=c(1,1,2,2,1,1,2,2))
df$F1<-as.factor(df$F1)
df$F2<-as.factor(df$F2)
ggplot(df, aes(x=X, y=Y, group=F1, color=F2))+geom_line()

一种解决方法可能是在我的数据框中添加一个新列,结合F1F2,但我不知道该怎么做。

【问题讨论】:

  • 我推荐使用facets,比如facet_grid

标签: r dataframe plot ggplot2 dplyr


【解决方案1】:

您说得对,您只能指定一个因素来控制分组。如果您想使用多个,可以使用interaction 函数来计算组合:

# you can either calculate the interaction beforehand and supply that...
df$F1F2 <- interaction(df$F1, df$F2)
ggplot(df, aes(x = X, y = Y, group = F1F2, color = F1F2)) + geom_line()

# or you can just drop it straight in!
ggplot(df,
  aes(x = X, y = Y, group = interaction(F1, F2), color = interaction(F1, F2))) +
  geom_line()

您还可以使用interaction 的参数来控制其格式(用于情节展示)。

或者,您可以找到其他方法来可视化多个因素。例如,您可以使用一个因子进行分组,然后使用facetting 显示另一个因子的水平(实际上是两个以上)。

【讨论】:

  • 谢谢。交互实际上是我一直在寻找的东西。
猜你喜欢
  • 2018-05-19
  • 1970-01-01
  • 2019-09-06
  • 2022-01-19
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 2022-01-17
  • 2019-01-23
相关资源
最近更新 更多