ggplot2饼图标签位置错误

Man*_*ndy 5 r ggplot2

样本数据

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

我尝试设置标签的位置。

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)) 
Run Code Online (Sandbox Code Playgroud)

但饼图实际上看起来像:

饼形图

Rom*_*man 7

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

在此输入图像描述

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

来自帮助:

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