0
votes

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

enter image description here

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.

2

2 Answers

1
votes

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

0
votes

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