R ggplot2-获取图例中的注释
我正在使用一个数据框,并使用ggplot生成一个饼图R ggplot2-获取图例中的注释,r,ggplot2,R,Ggplot2,我正在使用一个数据框,并使用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'),
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")
df%
总结(数量=总和(Cnt))%>%
突变(份额=数量/总和(数量)*100.0)%>%
排列(描述(体积))
dfc$Make这可以通过向比例填充酿酒机添加中断
和标签
来实现
首先,您将Make
映射到fill
,因此要控制颜色,您需要使用fill\u scale
。其次,如果要提供自定义图例条目,请在中定义图例中的键,并在标签中定义新名称:
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))
添加了标签,但是标签的顺序颠倒了。@user3206440最简单的解决方案是将rev
添加到标签
和断点
参数中。中指定的元素顺序决定了图例键条目的顺序。而标签
参数需要与breaks参数匹配。