【问题标题】:pie chart with ggplot2 with specific order and percentage annotations带有特定顺序和百分比注释的 ggplot2 饼图
【发布时间】:2020-12-18 23:58:14
【问题描述】:

我有一个如下所示的数据框

+--------+-----------+-----+
|  make  |   model   | cnt |
+--------+-----------+-----+
| toyota |  camry    |  10 |
| toyota |  corolla  |   4 |
| honda  |  city     |   8 |
| honda  |  accord   |  13 |
| jeep   |  compass  |   3 |
| jeep   |  wrangler |   5 |
| jeep   |  renegade |   1 |
| accura |  x1       |   2 |
| accura |  x3       |   1 |
+--------+-----------+-----+

我需要为每个品牌创建一个百分比份额(确实如此)。

我现在做以下事情。

library(ggplot2)
library(dplyr)

df <- data.frame(Make=c('toyota','toyota','honda','honda','jeep','jeep','jeep','accura','accura'),
                 Model=c('camry','corolla','city','accord','compass', 'wrangler','renegade','x1', 'x3'),
                 Cnt=c(10, 4, 8, 13, 3, 5, 1, 2, 1))
dfc <- df %>%
  group_by(Make) %>%
  summarise(volume = sum(Cnt)) %>%
  mutate(share=volume/sum(volume)*100.0) %>%
  arrange(desc(volume))

bp <- ggplot(dfc[c(1:10),], aes(x="", y= share, fill=Make)) +
  geom_bar(width = 1, stat = "identity")
pie <- bp + coord_polar("y")
pie

这给了我以下非常整洁的饼图。

但是我需要通过以下方式来增强它 - 如下图所示。

  1. 添加百分比标签
  2. share 的降序排列馅饼
  3. 删除 0/100、25 等标签
  4. 添加标题

【问题讨论】:

  • to 2. 根据您喜欢的顺序设置factor(share)levels。 4.重复的问题。
  • 3.与geom_text 合作,在您想要的地方获得您想要的东西。谷歌“piechart r” -> images -> 点击你喜欢的饼图图片。可能有您可以使用的代码。

标签: r ggplot2


【解决方案1】:

您必须将Make 的级别更改为sharevolume(提供的数据已排序):

dfc$Make <- factor(dfc$Make, levels = rev(as.character(dfc$Make)))

theme 参数一起玩:

ggplot(dfc[1:10, ], aes("", share, fill = Make)) +
    geom_bar(width = 1, size = 1, color = "white", stat = "identity") +
    coord_polar("y") +
    geom_text(aes(label = paste0(round(share), "%")), 
              position = position_stack(vjust = 0.5)) +
    labs(x = NULL, y = NULL, fill = NULL, 
         title = "market share") +
    guides(fill = guide_legend(reverse = TRUE)) +
    scale_fill_manual(values = c("#ffd700", "#bcbcbc", "#ffa500", "#254290")) +
    theme_classic() +
    theme(axis.line = element_blank(),
          axis.text = element_blank(),
          axis.ticks = element_blank(),
          plot.title = element_text(hjust = 0.5, color = "#666666"))

【讨论】:

  • 非常好!您将如何增加百分比标签的大小?
  • @Microscone 在geom_text 内更改大小。例如:geom_text(size = 10, ...)
【解决方案2】:

你可以试试:

df %>%
  group_by(Make) %>%
  summarise(volume = sum(Cnt)) %>%
  mutate(share=volume/sum(volume)) %>%
  ggplot(aes(x="", y= share, fill=reorder(Make, volume))) +
   geom_col() +
   geom_text(aes(label = scales::percent(round(share,3))), position = position_stack(vjust = 0.5))+
   coord_polar(theta = "y") + 
   theme_void()

添加 guides(fill = guide_legend(reverse = TRUE)) 以获得反转图例

【讨论】:

  • 饼图的顺序需要与份额百分比的顺序相同 - 所以本田应该排在前面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2022-07-22
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多