简体   繁体   中英

ggplot2 pie chart bad position of labels

Sample data

data <- data.frame(Country = c("Mexico","USA","Canada","Chile"), Per = c(15.5,75.3,5.2,4.0))

I tried set position of labels.

ggplot(data =data) +
geom_bar(aes(x = "", y = Per, fill = Country), stat = "identity", width = 1) +
coord_polar("y", start = 0) + 
theme_void()+ 
geom_text(aes(x = 1.2, y = cumsum(Per), label = Per)) 

But pie chart actually look like:

饼形图

You have to sort the data before calculating the cumulative sum. Then, you can optimize label position, eg by subtracting half of Per :

library(tidyverse)
data %>% 
  arrange(-Per) %>% 
  mutate(Per_cumsum=cumsum(Per)) %>% 
ggplot(aes(x=1, y=Per, fill=Country)) +
  geom_col() +
  geom_text(aes(x=1,y = Per_cumsum-Per/2, label=Per)) +
  coord_polar("y", start=0) + 
  theme_void()

在此输入图像描述

PS: geom_col uses stat_identity by default: it leaves the data as is.

Or simply use position_stack

data %>% 
  ggplot(aes(x=1, y=Per, fill=Country)) +
  geom_col() +
  geom_text(aes(label = Per), position = position_stack(vjust = 0.5))+
  coord_polar(theta = "y") + 
  theme_void()

在此输入图像描述

From the help:

# To place text in the middle of each bar in a stacked barplot, you
# need to set the vjust parameter of position_stack()

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