简体   繁体   中英

Add values to pie chart legend with ggplot2 in R

I have created a pie chart with ggplot in R plotting "Amounts" for 7 companies (A to G).

The data and code are the following:

# 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)) 

在此处输入图片说明

However, the labels for F and G are stacked on each other such that we can't read the values properly.

I would like to place those labels in the legend such that the legend reads as: A (41.1%) B (27.4%) C (13.7%) etc.

This could be achieved like so:

  1. Add a new colum by pasting the Company name and the proportion
  2. Map this new column on fill
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)) 

Thank you, this works.

I just had to modify subdata$legend_labs to a factor variable to keep the order in the legend (ie from highest amount, to lowest).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM