ggplot2饼图标签的位置不好

时间:2017-12-04 14:46:51

标签: r ggplot2

样本数据

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

我尝试设置标签的位置。

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

但饼图实际上看起来像是:

Pie chart

1 个答案:

答案 0 :(得分:3)

您必须在计算累积总和之前对数据进行排序。然后,您可以优化标签位置,例如通过减去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()

enter image description here

PS:geom_col默认情况下使用stat_identity:它会保留数据。

或者只使用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()

enter image description here

来自帮助:

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