gpt4 book ai didi

r - ggplot2 - 获取图例中的注释

转载 作者:行者123 更新时间:2023-12-04 03:02:42 25 4
gpt4 key购买 nike

我正在使用数据框并使用 ggplot 生成饼图。

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))
row_threshold = 2
dfc <- df %>%
group_by(Make) %>%
summarise(volume = sum(Cnt)) %>%
mutate(share=volume/sum(volume)*100.0) %>%
arrange(desc(volume))


dfc$Make <- factor(dfc$Make, levels = rev(as.character(dfc$Make)))
pie <- 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)) +
theme_classic() +
theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.title = element_text(hjust = 0.5, color = "#666666")) +
scale_color_brewer(palette = "Paired")

这给了我一个饼图,如下所示 - 我如何添加 %share 以及 Make 标签,例如 honda (45%) 而不仅仅是 honda

enter image description here

最佳答案

这可以通过向 scale_fill_brewer 添加 breakslabels 来实现。

首先,您将 Make 映射到 fill,因此要控制您需要使用 fill_scale 的颜色。其次,如果您想提供自定义图例条目,请在 breaks 中定义图例中存在的键,并在 labels 中定义新名称:

library(ggplot2)


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)) +
theme_classic() +
theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.title = element_text(hjust = 0.5, color = "#666666")) +
scale_fill_brewer(palette = "Paired",
labels = rev(paste0(dfc$Make, " (", round(dfc$share), "%)")),
breaks = rev(dfc$Make))

enter image description here

关于r - ggplot2 - 获取图例中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47765280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com