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

如何为ggplot绘制的饼图添加百分号并设置标签数字加粗?

Solution: Bold Percentage Labels in ggplot Pie Chart

Absolutely! You can easily add bold formatting and percentage symbols to your pie chart labels with two simple adjustments to your geom_text() layer. Here's the modified, working code:

# Load required packages
library(ggplot2)
# Optional: For cleaner percentage formatting
library(scales)

# Your original data frame
df <- structure(list(process = structure(16:1, .Label = c("A", "AA", "AAA", "AAAA", "AAAAA", "B", "BB", "BBB", "BBBB", "BBBBB", "BBBBBB", "C", "CC", "CCC", "CCCC", "CCCCC"), class = "factor"), percentage = c(1.869158879, 0.934579439, 5.046728972, 1.682242991, 0.747663551, 15.70093458, 1.869158879, 3.551401869, 3.738317757, 0.373831776, 2.61682243, 1.121495327, 13.45794393, 21.30841121, 14.76635514, 11.21495327 ), lab.ypos = c(0.9345794395, 2.3364485985, 5.327102804, 8.6915887855, 9.9065420565, 18.130841122, 26.9158878515, 29.6261682255, 33.2710280385, 35.327102805, 36.822429908, 38.6915887865, 45.981308415, 63.364485985, 81.40186916, 94.392523365)), class = "data.frame", row.names = c(NA, -16L))

# Modified plot code
ggplot(df, aes(x="", y=percentage, fill=process)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0) +
  # Updated geom_text with bold font and percentage symbols
  geom_text(
    aes(y = lab.ypos, label = paste0(round(percentage), "%")), 
    color = "white",
    fontface = "bold"  # This enables bold text
  )

Key Adjustments Explained:

  1. Bold Text: Added fontface = "bold" directly inside geom_text() — this tells ggplot to render the label text in bold.
  2. Percentage Symbols: Used paste0(round(percentage), "%") to append a "%" symbol to the rounded percentage value. If you want to keep decimal places (e.g., 1.9% instead of 2%), adjust the round() function or use the scales package for more control:
    # Example with 1 decimal place using scales
    geom_text(
      aes(y = lab.ypos, label = percent(percentage/100, accuracy = 0.1)), 
      color = "white",
      fontface = "bold"
    )
    
    Note: Since your percentage column already contains values as percentages (not proportions), we divide by 100 to convert to proportions for scales::percent().

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:09:55