将百分比标签放在图例旁边而不是切片中

时间:2018-07-25 17:29:59

标签: r ggplot2 legend

首先让我说饼图不是我的选择,这是主管要求的报告的一个方面。 我从以下代码创建了一系列饼图:

perpie <- Full_Mod_good %>%
  split(.$ServiceSite) %>%
  imap(function(data, site) {
    data %>%
    group_by(ServiceSite, InitialType) %>%
    summarise(count = n()) %>%
    mutate(share = round(count / sum(count), digits = 2)) %>%
    ggplot(aes(x = "", y = share, fill = InitialType)) +
    geom_col(width = 1) +
    geom_text(aes(label = scales::percent(share)), position = position_stack(vjust = 0.5)) +
    coord_polar(theta = "y", start = 0, direction = 1)+
    ggtitle(site)+
    ylab("Percentage of Healed Wounds")+
    xlab("")+
    theme_minimal()+
    theme(axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid  = element_blank())+
    theme(plot.title = element_text(hjust = 0.5))
        })
perpie 

大约有50个地块,如下所示: enter image description here

我想将百分比添加到图例中的标签,但是不确定如何执行此操作。我曾尝试将标签分布在图形的周围,但是由于初始类型数量众多,区分颜色相似的阴影有时会变得很困难。将百分比添加到图例将消除这种情况。

样本数据

ServiceSite.x InitialType
2   Dermatitis
2   Diabetic
2   Pressure Injury
2   Pressure Injury
3   Pressure Injury
3   Other
3   Laceration
3   Other
4   Pressure Injury
4   MASD
4   Blister (Non-Pressure)
4   Skin Tear
4   Pressure Injury
5   Skin Tear
5   Other
5   Contusion
5   Skin Tear
5   Surgical(Non-Healing)
5   Pressure Injury
6   Pressure Injury
1   Pressure Injury
6   Pressure Injury
6   MASD
1   Surgical(Non-Healing)
1   Pressure Injury
1   Skin Tear
1   Contusion

1 个答案:

答案 0 :(得分:2)

我对被迫进入饼图表示哀悼。您可以只添加带有百分比标签的列,然后将其用作填充变量。这是一个数据子集之一的示例(我之所以选择ServiceSite.x == 5是因为它有很多观测值可用于处理。

library(tidyverse)

df_label <- df %>%
  filter(ServiceSite.x == 5) %>%
  count(InitialType) %>%
  mutate(share = round(n / sum(n), digits = 2)) %>%
  mutate(label = scales::percent(share), labeled_type = sprintf("%s (%s)", InitialType, label))

df_label
#> # A tibble: 5 x 5
#>   InitialType               n share label labeled_type               
#>   <chr>                 <int> <dbl> <chr> <chr>                      
#> 1 Contusion                 1  0.17 17%   Contusion (17%)            
#> 2 Other                     1  0.17 17%   Other (17%)                
#> 3 Pressure                  1  0.17 17%   Pressure (17%)             
#> 4 Skin                      2  0.33 33%   Skin (33%)                 
#> 5 Surgical(Non-Healing)     1  0.17 17%   Surgical(Non-Healing) (17%)

ggplot(df_label, aes(x = 1, y = n, fill = labeled_type)) +
  geom_col(width = 1) +
  geom_text(aes(label = label), position = position_stack(vjust = 0.5)) +
  coord_polar(theta = "y") +
  theme_void()

reprex package(v0.2.0)于2018-07-25创建。