r - 在 R 中使用 ggplot2 向饼图图例添加值
问题描述
我用 R 中的 ggplot 创建了一个饼图,绘制了 7 家公司(A 到 G)的“金额”。
数据和代码如下:
# Data
data=data.frame('Company'=(c("A","B","C","D","E","F","G")),'Amount'=c(30,20,10,5,5,2,1))
data=data %>% mutate(Company= factor(x = Company, levels = Company)) %>%
mutate(prop = Amount / sum(data$Amount) ) %>% mutate(ypos = cumsum(prop)- 0.5*prop )
# Pie chart
library(ggplot2)
ggplot(data, aes(x="", y=Amount, fill= Company) )+
geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0,direction = -1) + theme_void() +
#geom_text(aes(label = percent(prop) ), size=3, position=position_stack(vjust=0.5)) +
labs(x = NULL, y = NULL, fill = NULL) + scale_fill_brewer(palette="Blues", direction=-1) +
geom_text(aes(label = percent(prop) ), size=3, position=position_stack(vjust=0.5))
但是,F 和 G 的标签相互堆叠,因此我们无法正确读取值。
我想将这些标签放在图例中,使图例显示为:A (41.1%) B (27.4%) C (13.7%) 等。
解决方案
这可以像这样实现:
- 通过粘贴公司名称和比例添加新列
- 将此新列映射到填充
library(ggplot2)
library(dplyr)
library(scales)
# Data
data=data.frame('Company'=(c("A","B","C","D","E","F","G")),'Amount'=c(30,20,10,5,5,2,1))
data=data %>% mutate(Company= factor(x = Company, levels = Company)) %>%
mutate(prop = Amount / sum(data$Amount) ) %>%
mutate(ypos = cumsum(prop)- 0.5*prop) %>%
mutate(legend_labs = paste0(Company, " (", percent(prop), ")"))
# Pie chart
library(ggplot2)
ggplot(data, aes(x="", y=Amount, fill= legend_labs) )+
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0, direction = -1) +
theme_void() +
labs(x = NULL, y = NULL, fill = NULL) +
scale_fill_brewer(palette="Blues", direction=-1) +
geom_text(aes(label = percent(prop) ), size=3, position=position_stack(vjust=0.5))
推荐阅读
- postman - 使用 reCaptcha 提交 Postman Google 表单
- python-3.x - 使用字符串切片的longestPalindromeSubstring 的时间复杂度是多少?
- java - 带有 Spring Boot 的 Microsoft Graph api 邮件服务
- jboss - JBPM_7.XX:如何将角色名称“admin”更改为其他名称?
- php - 如何在 yii2 特定目标页面中取消链接 js 文件?
- c - 如何使用 mmap 将新条目映射到用户空间内存区域,以便用户级进程可以读取和写入内核空间?
- php - 当用户使用 ajax 在 laravel 中选择任何下拉值时,如何立即显示数据库详细信息?
- javascript - 我在我的 html 画布上重绘一些圆圈时遇到问题
- android-camera - 应该使用什么颜色格式来编码媒体编解码器中libyuv转换的i420帧?
- amazon-web-services - AWS AutoScaling 组 Node.js 服务器运行状况不佳