首先我要说的是,饼图不是我的选择,它是主管要求的报告的一个方面。 我有一系列由以下代码创建的饼图:
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
我想将百分比添加到图例中的标签,但不确定如何执行此操作。我尝试将标签分布在图表的周边,但由于初始类型数量众多,有时区分相似的颜色深浅变得很困难。将百分比添加到图例中可以消除这种情况。
示例数据
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
最佳答案
我对被迫绘制饼图表示哀悼。您只需添加一个带有包含百分比的标签的列,然后将其用作填充变量。这是一个包含数据子集之一的示例(我选择 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 创建于 2018-07-25 (v0.2.0)。
关于r - 将百分比标签放在图例旁边而不是切片中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51524641/