【问题标题】:Most efficient way of getting bar chart with percentage labels with ggplot使用ggplot获取带有百分比标签的条形图的最有效方法
【发布时间】:2020-06-29 11:36:25
【问题描述】:

我有一个问题更针对于创建带有百分比标签和预期布局的条形图的最有效方法。我有一个包含几列的数据框,其中包括“经济”列。该列确实有五个值“非常好”、“好”、“坏”、“非常坏”和“不知道”。这是可重现的数据:

structure(c(3L, 3L, 3L, 3L, 2L, 3L, 4L, 4L, 4L, 4L, 3L, 2L, 2L, 
2L, 3L, 2L, 4L, 4L, 2L, 3L, 4L, 3L, 4L, 4L, 3L, 2L, 2L, 3L, 3L, 
3L, 3L, 4L, 4L, 4L, 3L, 2L, 4L, 3L, 3L, 3L, 3L, 3L, 4L, 3L, 4L, 
2L, 4L, 4L, 3L, 2L), .Label = c("Very good", "Good", "Bad", "Very bad", 
"Don't know"), class = "factor")

我使用此代码获得了预期的结果:

lebanon %>%
  filter(!is.na(economy), economy != "Don't know") %>%
  count(economy) %>%
  mutate(prop = n / sum(n)) %>%
  ggplot(aes(economy, y = prop, fill = economy)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("darkgreen", "green4", "red3", "red4")) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = scales::percent(prop, suffix = "")),
            position=position_dodge(width=0.9), vjust=-0.5, size = 5) +
  labs(x = "", y = "", fill = "") +
  theme_minimal() +
  theme(axis.text.x = element_text(size = 15),
        axis.text.y = element_text(size = 15),
        legend.text = element_text(size = 15))

得到这个情节:

我想知道这是否是使用所需布局将计数重新计算为百分比的最有效方法。我使用了 count 函数和 mutate,但我也知道可能有其他方法可以使用 stat(prop) 和 ..count.. 函数来处理这个问题。问题是当我使用 stat(prop) 或 fill = "prop" 时,它没有使用 scale_fill_manual 函数。

所以我的问题是,在没有太多中间步骤来计算百分比的情况下,获得所需条形图(上图)的最有效方法是什么。如果我的问题没有明确提出,请提前道歉。 :)

问候

【问题讨论】:

  • 您的示例不可重现。您提供的是factor,而不是data.framefactor 不包含任何值为“非常好”的观察值,但您的图表包含。
  • 可能是因为在 2400 行的数据集中只有很少的观察值具有该值。

标签: r ggplot2 dplyr


【解决方案1】:

GGally 中的新统计stat_prop() 专为轻松计算比例而设计。更多详情http://ggobi.github.io/ggally/articles/ggally_stats.html#stat-prop-

by 美学表示分母。这里是by = 1,因为你想要总数的 %。

如果您添加一个构面,则所有比例将分别计算每个构面。

在您的情况下,您可以尝试类似

library(ggplot2)
library(GGally)

ggplot(lebanon) +
  aes(x = economy, y = after_stat(prop), fill = economy, by = 1) +
  geom_bar(stat = "prop") +
  geom_text(aes(label = scales::percent(after_stat(prop))), stat = "prop", vjust=-0.5)

【讨论】:

    【解决方案2】:

    您可以尝试此解决方案。我使用了你的数据样本。我希望这可以帮助:

    library (ggplot2)
    library(scales)
    
    lebanon %>%
      filter(!is.na(economy), economy != "Don't know") %>%
      ggplot(aes(x= economy)) + 
      geom_bar(aes(y = (..count..)/sum(..count..), fill = economy), stat="count") +
      geom_text(aes( label = scales::percent((..count..)/sum(..count..)),
                     y= (..count..)/sum(..count..) ), stat= "count", vjust = -.5) +
      labs(y = "Percent", fill="Economy") +
      scale_y_continuous(labels = scales::percent)
    

    我还发现了这个包可以帮助你:http://larmarange.github.io/JLutils/reference/stat_fill_labels.html

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 2021-07-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多