gpt4 book ai didi

r - ggplot2饼图标签的错误位置

转载 作者:行者123 更新时间:2023-12-03 20:22:29 24 4
gpt4 key购买 nike

样本数据

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

最佳答案

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

关于r - ggplot2饼图标签的错误位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47635919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com