【问题标题】:Fill Percent stacked barchart according to value of each group, R根据每组的值填充百分比堆积条形图,R
【发布时间】:2021-10-16 20:05:51
【问题描述】:

我再次对百分比堆积条形图有疑问。这次我有这个数据:

structure(list(month.int = 1:12, n = c(14L, 28L, 19L, 35L, 31L, 
62L, 96L, 44L, 15L, 38L, 127L, 14L), share = c(0.0267686424474187, 
0.0535372848948375, 0.0363288718929254, 0.0669216061185468, 0.0592734225621415, 
0.118546845124283, 0.183556405353728, 0.0841300191204589, 0.0286806883365201, 
0.0726577437858509, 0.24282982791587, 0.0267686424474187), month = structure(1:12, .Label = c("Jan", 
"Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", 
"Nov", "Dec"), class = "factor"), x = c("month", "month", "month", 
"month", "month", "month", "month", "month", "month", "month", 
"month", "month")), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

其中的代码如下:

ggplot(df, aes(fill = month,
               x = x,
               y = share)) +
  scale_fill_viridis_d() +
  geom_bar(position = "fill",
           stat = "identity",
           color = "black",
           show.legend = F) +
  geom_text(
    aes(
      label = glue("{month}: {round(share, 2)}"),
      group = month
    ),
    position = position_stack(vjust=.5)
  ) +
  theme_void()

制作这个情节:

但是,我想根据nshare中的值填充每个月的矩形。

我试过了:

ggplot(df, aes(fill = factor(n, ordered = T),
               x = x,
               y = share)) +
  scale_fill_viridis_d() +
  geom_bar(position = "fill",
           stat = "identity",
           color = "black",
           show.legend = F) +
  geom_text(
    aes(
      label = glue("{month}: {round(share, 2)}"),
      group = month
    ),
    position = position_stack(vjust=.5)
  ) +
  theme_void()

但它实际上只是让事情变得更糟......

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    好的,当我这样做时:

    ggplot(df, aes(fill = n,
                   x = x,
                   y = share)) +
      scale_fill_viridis_c() +
      geom_bar(position = "fill",
               stat = "identity",
               color = "black",
               show.legend = F) +
      geom_text(
        aes(
          label = glue("{month}: {round(share, 2)} ({n})"),
          group = month %>% rev()
        ),
        family = "Times",
        position = position_stack(vjust=.5)
      ) +
      theme_void()
    

    但我怀疑这是最好的答案?

    我个人不明白为什么将 12 月绘制在顶部而将 1 月绘制在底部。以及为什么我需要反转文本以使其适合... 任何解释都会非常受欢迎:)

    【讨论】:

    • 问题是当在fill 上映射n 时,您的条形不再按month 分组。这可以通过在ggplot() 中添加group=monthaes() 来解决。在这种情况下,您也可以从 geom_text() 中删除 group
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2015-01-16
    • 2019-09-27
    相关资源
    最近更新 更多