繁体   English   中英

ggplot2饼图标签的位置不好

[英]ggplot2 pie chart bad position of labels

样本数据

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

但饼图实际上看起来像:

饼形图

您必须在计算累积总和之前对数据进行排序。 然后,您可以优化标签位置,例如减去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默认使用stat_identity:它按geom_col保留数据。

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

在此输入图像描述

从帮助:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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