我正在尝试将计数/百分比添加到饼图的图例标签中。饼图非常糟糕,我知道,但这不是本文的重点。我想将“ Count”的值粘贴到图例上的“ Wound.Type”标签上,但无法弄清楚如何为以下代码的每次迭代访问Counts。目标将是类似于“ 5级”的目标或其他任何数字。我已经尝试过“。〜Count”和“。〜Wound.Type”,“。$ Count”和“。$ Wound.Type”,但是我不知道如何访问我想要的特定值。
p1 <- DF %>%
split(.$ServiceSite) %>%
imap(function(data, site) {
data %>%
group_by(ServiceSite, Wound.Type) %>%
summarise(Count = n()) %>%
mutate(share = round(Count / sum(Count), digits = 2)) %>%
ggplot(aes(x = "", y = Count, fill = Wound.Type)) +
geom_col(width = 1) +
scale_fill_discrete(labels = paste(.$Wound.Type, .$Count))+
facet_grid(facets = .~ServiceSite, labeller = label_value)+
geom_text(aes(label = Count, y = ), position = position_stack(vjust = 0.5)) +
coord_polar(theta = "y")+
labs(caption = "Visits from 1/1/18-6/30/18")+
ggtitle("Count of Unique Wound Occurrences")+
theme(plot.caption = element_text(size= 8, hjust = .5))+
theme(plot.title = element_text(hjust = 0.5))+
theme(plot.subtitle = element_text(hjust = 0.5))+
ylab("")+
xlab("")+
theme(axis.text = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank())
})
p1
数据:
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
答案 0 :(得分:1)
通常,您可以为此使用函数参数。由于data
参数引用数据集,因此您可以直接引用原始数据集中的变量。在您的示例中为data$Wound.Type
。
但是,您在函数内动态添加了Count
变量,因此该变量不在传递给data
参数的数据集中。您可以在函数中创建一个新对象,而不是将数据集直接传递到ggplot()
。这将使您可以引用此“变异”数据集中的变量。
这里是一个示例,其中我创建了一个名为dat2
的新数据集,该数据集在ggplot()
中使用,可以用于fill
名称。
对该功能的关键更改是在该功能内创建一个新对象:
dat2 = data %>%
group_by(ServiceSite, Wound.Type) %>%
summarise(Count = n()) %>%
mutate(share = round(Count / sum(Count), digits = 2))
并将该对象用于fill
标签:
scale_fill_discrete(labels = paste(dat2$Wound.Type, dat2$Count))
这些更改以及您的其余部分:
DF %>%
split(.$ServiceSite) %>%
imap(function(data, site) {
dat2 = data %>%
group_by(ServiceSite, Wound.Type) %>%
summarise(Count = n()) %>%
mutate(share = round(Count / sum(Count), digits = 2))
ggplot(dat2, aes(x = "", y = Count, fill = Wound.Type)) +
geom_col(width = 1) +
scale_fill_discrete(labels = paste(dat2$Wound.Type, dat2$Count))+
facet_grid(facets = .~ServiceSite, labeller = label_value)+
geom_text(aes(label = Count, y = ), position = position_stack(vjust = 0.5)) +
coord_polar(theta = "y")+
labs(caption = "Visits from 1/1/18-6/30/18")+
ggtitle("Count of Unique Wound Occurrences")+
theme(plot.caption = element_text(size= 8, hjust = .5))+
theme(plot.title = element_text(hjust = 0.5))+
theme(plot.subtitle = element_text(hjust = 0.5))+
ylab("")+
xlab("")+
theme(axis.text = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank())
})