【问题标题】:Two piecharts side by side in RR中并排的两个饼图
【发布时间】:2020-10-07 18:54:50
【问题描述】:

我需要两张饼图并排显示德国两个县的 Covid19 病例、治愈和死亡的百分比。一个县在左边,另一个在右边。

到目前为止,我的代码如下所示:

RKI_COVID19 %>% 
  group_by(Landkreis) %>%
  summarise(fraction_active = (sum(AnzahlFall)-sum(AnzahlGenesen))/sum(AnzahlFall),
            fraction_cured = sum(AnzahlGenesen)/sum(AnzahlFall),
            fraction_death = sum(AnzahlTodesfall)/sum(AnzahlFall)) %>%
  subset(Landkreis == "SK Wolfsburg" | Landkreis == "SK Münster") %>%
  gather("Type", "Value", -Landkreis) %>%  # convert to long format
  ggplot(aes(Landkreis, Value, fill = Type)) +
  geom_col(position = "dodge") +
  geom_bar(stat = "identity", position = position_fill()) +
  geom_text(aes(label = round(Value, 2)), size = 3, position = position_fill(vjust = 0.5)) +
  facet_wrap(~Landkreis) +
  coord_polar("y")  

在子集()之后,我有所有我感兴趣的值:

 Landkreis    fraction_active fraction_cured fraction_death
  <chr>                  <dbl>          <dbl>          <dbl>
1 SK Münster             0.108          0.892         0.0115
2 SK Wolfsburg           0.129          0.871         0.118 

通过使用gather(),我将它们转换为长格式并创建两个并排的条形图。 这很好用。

在最后两行使用 facet_wrap() 和 coord_polar() 时会出现问题。

然后我的饼图如下所示:

One small and one donut pie-chart

任何想法如何创建两个相同大小的饼图?

【问题讨论】:

  • 问题是你在 x 上映射 Landkreis。尝试ggplot(aes(2, Value, fill = Type)) 以获得相同的大小和+ xlim(0.5, 2.5) 使其成为甜甜圈。见here

标签: r pie-chart


【解决方案1】:

我已经用一个我刚刚命名为“n”的虚拟变量实现了这一点:

df = tribble(
  ~n, ~cat, ~act, ~cur, ~dea,
  1, "A", 0.1, 0.8, 0.1,
  1, "B", 0.05, 0.9, 0.05
) %>%
  pivot_longer(cols = c(act,cur,dea))

ggplot(df, aes(n, value, fill = name)) +
  geom_bar(stat = "identity", position = position_fill()) +
  geom_text(aes(label = round(value, 2)), size = 3, position = position_fill(vjust = 0.5)) +
  facet_wrap(~cat) +
  coord_polar("y")

这给了我:

然后您可以使用theme() 删除“n”轴

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 2020-04-27
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多