如何为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:
- Bold Text: Added
fontface = "bold"directly insidegeom_text()— this tells ggplot to render the label text in bold. - 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 theround()function or use thescalespackage for more control:
Note: Since your# Example with 1 decimal place using scales geom_text( aes(y = lab.ypos, label = percent(percentage/100, accuracy = 0.1)), color = "white", fontface = "bold" )percentagecolumn already contains values as percentages (not proportions), we divide by 100 to convert to proportions forscales::percent().
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

