【问题标题】:How can I use ggplot to produce multiple plots within one pipe如何使用 ggplot 在一个管道内生成多个图
【发布时间】:2021-09-25 01:31:13
【问题描述】:

所以我使用 ggplot 创建三个不同的图,它们使用相同的数据框。一切都与另一个非常相似。下面的代码工作得很好。但是,我对一遍又一遍地重复它们感到难过。有什么办法可以简化一下吗?

wday cat_number cat_size cat_age
Mon some number not important some number
Tue some number not important some number
smelly_cat %>%
  ggplot(aes(x=wday, y=cat_number)) +
  geom_bar()
smelly_cat %>%
  ggplot(aes(x=wday,y=cat_size)) +
  geom_bar()
smelly_cat %>%
  ggplot(aes(x=wday,y=cat_age)) +
  geom_bar()

【问题讨论】:

  • 好像表格格式刚刚崩溃
  • 但想法是 wday 和 cat_size、cat_age、cat_number 只是数据框中的不同列

标签: r ggplot2 dplyr


【解决方案1】:

这里以iris 为例。

library(ggplot2)
library(dplyr)
library(reshape2)

df <- iris %>%
  group_by(Species) %>%
  summarize(across(everything(), mean))
df <- melt(df, id.vars = "Species")

我正在使用 reshape2 的melt() 来获取这张表:

      Species     variable value
1      setosa Sepal.Length 5.006
2  versicolor Sepal.Length 5.936
3   virginica Sepal.Length 6.588
4      setosa  Sepal.Width 3.428
5  versicolor  Sepal.Width 2.770
6   virginica  Sepal.Width 2.974
7      setosa Petal.Length 1.462
8  versicolor Petal.Length 4.260
9   virginica Petal.Length 5.552
10     setosa  Petal.Width 0.246
11 versicolor  Petal.Width 1.326
12  virginica  Petal.Width 2.026

现在所有 y 值都在同一列中,我可以绘制它们。然后,您可以在 aes() 中使用 fill 来定义分组变量。像这样:

ggplot(df, aes(x=Species,y=value,fill=variable)) +
  geom_bar(position = "dodge", stat = "identity")

在您的geom_bar() 中定义定位(“堆叠”用于堆叠条,“躲避”用于分组条)并使用stat = "identity" 不让 R 进行任何聚合。

如果您的 y 值在不同的范围内,您可能不希望将它们放在同一个图表中。您可以使用facet_grid() 将它们分开,如下所示:

ggplot(df, aes(x=Species,y=value)) +
  geom_bar(stat = "identity") + facet_grid(. ~ variable)

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多