You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ggplot2环形图中添加扇区中心到外部标签的虚线

解决方案:环形图添加径向虚线连接文本

步骤说明

要实现从环形扇区到外部文本的虚线,核心是先计算每个扇区的中心位置(对应极坐标中的角度位置),再用geom_segment绘制径向线段。

修改后的完整代码

library(ggplot2)
library(dplyr)

# 原始数据
COUNTRY <- c("Sweden", "France", "USA", "Britain", "Argentina", "Brazil")
Revenue <- c(190, 146, 131, 129, 121, 937)
Percent <- c(0.11487304, 0.08827086, 0.07920193, 0.07799274, 0.07315599, 0.56650544)
color <- c('A', 'B', 'C', 'D', 'E', 'F')

TOP_5 <- data.frame(COUNTRY, Revenue, Percent, color) %>%
  # 计算每个扇区的中心位置(极坐标角度对应的值)
  mutate(
    cum_perc = cumsum(Percent),
    mid_perc = cum_perc - Percent/2
  )

colors <- c('A'='#D9553B', 'B'='#E17A65', 'C'='#EBA799', 'D'='#F2C8C0', 'E'='#F9E3DF', 'F'='#A7A8A9')

PLOT <- ggplot(data = TOP_5, aes(x = 2, y = Percent, fill = color)) +
  geom_col(color = "white") +
  coord_polar("y", start = 1) +
  # 添加径向虚线:从环形外边缘(x=2)到文本位置附近(x=3),沿扇区中心角度(mid_perc)
  geom_segment(aes(x = 2, xend = 3, y = mid_perc, yend = mid_perc),
               linetype = "dashed", color = "#B43C23") +
  geom_point(position = position_stack(vjust = 0.5), 
             color = "#B43C23", 
             size = 3) +
  geom_text(aes(x = 3, label = paste0(" ", round(Percent * 100), "%")), 
            position = position_stack(vjust = 0.5), 
            hjust = 0,
            angle = 0,
            color = "black") +
  geom_text(aes(x = 3, label = COUNTRY), 
            position = position_stack(vjust = 0.5), 
            hjust = 1, 
            angle = 0,
            color = "#B43C23") +
  theme(panel.background = element_blank(),
        axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank(),
        plot.title = element_text(hjust = 0.5, size = 18)) +
  scale_fill_manual(values = colors) +
  theme(legend.position = "none") +
  xlim(0.5, 3.2)  

PLOT

关键细节解释

  1. 计算扇区中心位置:通过cumsum(Percent)得到累积百分比,再减去每个扇区百分比的一半,得到每个扇区的中心对应的极坐标y值(mid_perc),这个值和position_stack(vjust=0.5)的对齐逻辑完全一致。
  2. 绘制径向虚线:geom_segment中,x=2对应环形图的外半径,xend=3对应文本所在的半径位置,y和yend都设为mid_perc,确保线段沿扇区中心的径向延伸,设置linetype="dashed"实现虚线效果。

内容的提问来源于stack exchange,提问作者Matt0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 21:07:39