【问题标题】:How to create scaled and faceted clustered bargraphs of a summarized dataframe in ggplot2?如何在 ggplot2 中创建汇总数据框的缩放和多面聚集条形图?
【发布时间】:2020-07-14 03:22:46
【问题描述】:

我正在尝试创建一个条形图网格,以显示不同物种的平均值。我正在为这个问题使用iris 数据集。

我总结了数据,将其融合成长形,并尝试使用facet_wrap

iris %>%
  group_by(Species) %>%
  summarise(M.Sepal.Length=mean(Sepal.Length),
            M.Sepal.Width=mean(Sepal.Width),
            M.Petal.Length= mean(Petal.Length),
            M.Petal.Width=mean(Petal.Width)) %>%
  gather(key = Part, value = Value,  M.Sepal.Length:M.Petal.Width) %>%
ggplot(., aes(Part, Value, group = Species, fill=Species)) +
  geom_col(position = "dodge") + 
  facet_grid(cols=vars(Part)) + 
  facet_grid(cols = vars(Part))

但是,我得到的图表有 x.axis 标签,这些标签串在每个方面网格上。此外,聚类图不在每个构面框内居中。相反,它们出现在各自 x 轴标签的位置。我想去掉 x 轴标签,使图表居中,并在每个方面内缩放图表。

这是结果图的图像,上面标有我的预期输出:

【问题讨论】:

  • 嗨 Max,欢迎来到 Stack Overflow。如果您使用dput(df) 提供至少一个数据样本,或者如果您的数据非常大dput(df[1:20,]),那么提供帮助会容易得多。您可以edit您的问题并粘贴输出。请用三个反引号(```)包围输出以获得更好的格式。在绘画或预览中模拟您的预期图表也可能会有所帮助。请参阅How to make a reproducible example 了解更多信息。
  • @IanCampbell 好的,听起来不错!我切换到 iris 数据集。

标签: r ggplot2 dplyr


【解决方案1】:

也许这就是你要找的东西?

主要变化是:

  1. 删除 Part 作为映射到 x 的变量,这样数据就会绘制在每个方面的相同位置
  2. 切换到facet_wrap,这样你就可以使用scales = "free_y"
  3. 使用labs手动添加x标题
  4. 添加 theme 以消除 x 轴刻度和刻度标签。
library(ggplot2)
library(dplyr) # Version >= 1.0.0
iris %>%
    group_by(Species) %>%
    summarise(across(1:4, mean, .names = "M.{col}")) %>%
    gather(key = Part, value = Value,  M.Sepal.Length:M.Petal.Width) %>%
ggplot(., aes(x = 1, y = Value, group = Species, fill=Species)) +
  geom_col(position = "dodge") + 
  facet_wrap(.~Part, nrow = 1, scales = "free_y") +
  labs(x = "Part") + 
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank()) 

我还冒昧地使用新的 across 功能将您的手动呼叫切换到 summarise

您还可以通过以下方式计算误差线:

library(tidyr)
iris %>%
    group_by(Species) %>%
    summarise(across(1:4, list(M = mean, SE = ~ sd(.)/sqrt(length(.))),
                     .names = "{fn}_{col}")) %>%
    pivot_longer(-Species, names_to = c(".value","Part"),
                 names_pattern = "([SEM]+)_(.+)") %>% 
ggplot(., aes(x = 1, y = M, group = Species, fill=Species)) +
  geom_col(position = "dodge") + 
  geom_errorbar(aes(ymin = M - SE, ymax = M + SE), width = 0.5,
                position = position_dodge(0.9)) +
  facet_wrap(.~Part, nrow = 1, scales = "free_y") +
  labs(x = "Part", y = "Value") + 
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank()) 

【讨论】:

  • 谢谢!是否可以在同一个“收集”函数中添加标准误差以将误差线添加到图表中?这将如何运作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多