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

R Shiny环形图中geom_label标签错位及图例多余字符问题求解

问题修复方案

问题根因

  • 图例出现多余"a"字符:geom_label默认会将标签样式同步渲染到图例中,只需关闭该图层的图例展示即可解决。
  • 标签位置不匹配扇区:极坐标下堆叠环形图的标签默认未对齐扇区中心,需要指定堆叠定位参数计算每个扇区的中点坐标。

修复代码(普通geom_label版本,无需额外包)

library(shiny)
library(dplyr)
library(ggplot2)
library(Cairo)
options(shiny.usecairo=T) 

my_colors <- c("#00A3AD", "#FF8200", "#753BBD", "#6CC24A")

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            
        ),
        mainPanel(
            fluidRow(
                plotOutput("count_by_person")

            ))
    ))
server <- function(input, output) {
    
    
    output$count_by_person <- renderPlot({
        
        data <- tibble(name = c("Justin", "Corey", "Sibley", "Kate"),
                       n = c(10, 30, 59, 1),
                       prop = c(10, 30, 59, 1))

        ggplot(data, aes(x = 2, y = prop, fill = name)) +
            geom_bar(stat = "identity", color = "white") +
            coord_polar(theta = "y", start = 0)+
            # 新增两个参数修复问题
            geom_label(aes(label = paste0(n, "\n", prop, "%")),
                       position = position_stack(vjust = 0.5), # 对齐扇区中心
                       show.legend = FALSE) + # 关闭标签图层的图例展示
            scale_fill_manual(values = my_colors) +
            theme_void() +
            xlim(.5, 2.5)
    })
    
}
shinyApp(ui, server)

修复代码(geom_label_repel带引导线版本)

如果需要标签放在环形外侧加引导线的效果,可以使用如下修改后的代码:

library(shiny)
library(dplyr)
library(ggplot2)
library(Cairo)
library(ggrepel)
options(shiny.usecairo=T) 

my_colors <- c("#00A3AD", "#FF8200", "#753BBD", "#6CC24A")

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            
        ),
        mainPanel(
            fluidRow(
                plotOutput("count_by_person")

            ))
    ))
server <- function(input, output) {
    
    
    output$count_by_person <- renderPlot({
        
        data <- tibble(name = c("Justin", "Corey", "Sibley", "Kate"),
                       n = c(10, 30, 59, 1),
                       prop = c(10, 30, 59, 1)) %>%
          # 预先计算每个扇区的中心y坐标
          arrange(desc(name)) %>%
          mutate(y_center = cumsum(prop) - prop/2)

        ggplot(data, aes(x = 2, y = prop, fill = name)) +
            geom_bar(stat = "identity", color = "white") +
            coord_polar(theta = "y", start = 0)+
            geom_label_repel(aes(y = y_center, label = paste0(n, "\n", prop, "%")),
                             nudge_x = 0.5,
                             show.legend = FALSE) +
            scale_fill_manual(values = my_colors) +
            theme_void() +
            xlim(.5, 3) # 扩大x轴范围容纳外侧标签
    })
    
}
shinyApp(ui, server)

内容的提问来源于stack exchange,提问作者J.Sabree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 05:45:03