饼图与ggplot2具有特定的顺序和百分比注释

时间:2017-12-11 11:32:58

标签: r ggplot2

我有一个如下数据框

+--------+-----------+-----+
|  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

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

enter image description here

但是我需要通过以下方式加强这一点 - 如下图所示。

  1. 添加百分比标签
  2. 按照share
  3. 的顺序排序馅饼
  4. 删除标签,如0 / 100,25
  5. 添加标题
  6. enter image description here

2 个答案:

答案 0 :(得分:12)

您必须按Makeshare更改volume的级别(提供的数据已经排序):

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"))

enter image description here

答案 1 :(得分:3)

您可以尝试:

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

enter image description here