如何调整ggplot饼图标签位置:解决停靠型自行车标签可读性问题
解决方案
核心原因
position_stack在极坐标下的行为和直角坐标不同,直接调整vjust无法实现垂直方向的位置偏移,需要通过计算饼块中心位置或调整x轴参数来实现需求。
1. 单独调整docked bike标签位置
先在数据处理阶段计算每个饼块的中心位置,再针对docked bike标签单独设置y轴偏移量:
数据处理(补充位置计算)
library(tidyverse) library(scales) user_type_ride_type <- clean_rides %>% group_by(rideable_type, member_casual) %>% summarise(number_of_rides = n(), total_ride_time = sum(ride_length), average_ride_time = mean(ride_length)) %>% mutate(percentage = case_when( member_casual == "casual" ~ round(number_of_rides / sum(number_of_rides) * 100, 0), member_casual == "member" ~ round(number_of_rides / sum(number_of_rides) * 100, 0) )) %>% ungroup() casual_data <- user_type_ride_type %>% filter(member_casual == "casual") %>% arrange(rideable_type) %>% # 计算累积骑行次数,推导每个饼块的中心位置 mutate(cum_rides = cumsum(number_of_rides), center = cum_rides - number_of_rides/2)
绘图代码(调整单个标签)
ggplot(casual_data, aes(x = "", y = number_of_rides, fill = rideable_type)) + geom_bar(stat = "identity", width = 1) + scale_fill_manual(values = c("#00C19F", "#D7EF16", "#9100B1"), labels = c("classic bike", "electric bike", "docked bike")) + coord_polar("y", start=0) + # 绘制普通标签 geom_text(data = filter(casual_data, rideable_type != "docked bike"), aes(label = comma(number_of_rides), y = center), size = 4) + # 单独调整docked bike标签,通过y轴偏移上移(偏移量根据数据量级调整) geom_text(data = filter(casual_data, rideable_type == "docked bike"), aes(label = comma(number_of_rides), y = center + 50000), size = 4) + labs(title = "Total Rides by Bike Type for Casual Users", fill = "Bike Type", caption = "Data Source: Motivate International Inc") + theme_void() + theme(legend.position = "bottom", plot.caption.position = "plot", plot.caption = element_text(color = "gray", hjust = 3.8, vjust = 1))
2. 将所有标签移至饼图外缘
通过设置标签的x值大于1(饼图默认x轴范围是0-1),配合position_stack对齐饼块中心线,即可将标签移到外侧:
绘图代码
ggplot(casual_data, aes(x = "", y = number_of_rides, fill = rideable_type)) + geom_bar(stat = "identity", width = 1) + scale_fill_manual(values = c("#00C19F", "#D7EF16", "#9100B1"), labels = c("classic bike", "electric bike", "docked bike")) + coord_polar("y", start=0) + # x=1.2将标签放在饼图外侧,vjust=0.5确保标签对齐饼块中心 geom_text(aes(label = comma(number_of_rides), x = 1.2), position = position_stack(vjust = 0.5), size = 4) + labs(title = "Total Rides by Bike Type for Casual Users", fill = "Bike Type", caption = "Data Source: Motivate International Inc") + theme_void() + theme(legend.position = "bottom", plot.caption.position = "plot", plot.caption = element_text(color = "gray", hjust = 3.8, vjust = 1))
关键说明
- 调整单个标签时,
center + 50000中的偏移量需要根据你的数据量级调整,数值越大标签上移越多 - 移至外缘时,
x=1.2可根据饼图大小修改,值越大标签离饼图越远;position_stack(vjust=0.5)保证标签在每个饼块的中心线上
内容的提问来源于stack exchange,提问作者Marinda_L
相关产品推荐
相关产品推荐

