【发布时间】:2016-07-31 11:02:05
【问题描述】:
我正在尝试向圆环图添加百分比标签,但未能成功绘制清晰的百分比值表示(四舍五入且不重叠)
## my data
library(ggplot2)
col <- c("white", "black", "transparent", "grey", "blue", "yellow", "green", "red", "pink", "orange", "brown")
freq <- c(101, 68, 34, 18, 14, 5, 5, 3, 2, 1, 1)
## create data frame
colour.df <- data.frame(col, freq)
colour.df
## calculate percentage
colour.df$percentage = colour.df$freq / sum(colour.df$freq)* 100
colour.df = colour.df[rev(order(colour.df$percentage)), ]
colour.df$ymax = cumsum(colour.df$percentage)
colour.df$ymin = c(0, head(colour.df$ymax, n = -1))
colour.df
## reorder colour levels
colour.df$col <- reorder(colour.df$col,
new.order = c(10, 1, 9, 5, 2, 11, 4, 8, 7, 6, 3))
一切准备就绪。我可能以一种特殊的方式做到了这一点,因为我必须为其他涉及颜色的类别制作多个甜甜圈,但我无法理解(方面?)。
## DONUNT ##
donut = ggplot(colour.df, aes(fill = col, ymax = ymax, ymin = ymin, xmax = 100, xmin = 80)) +
geom_rect(colour = "black") +
coord_polar(theta = "y") +
xlim(c(0, 100)) +
geom_label(aes(label = paste(percentage,"%"), x = 100, y = (ymin + ymax)/2),
inherit.aes = F, show.legend = F, size = 5) +
theme(legend.title = element_text(colour = "black", size = 16, face = "bold"),
legend.text = element_text(colour = "black", size = 15),
panel.grid = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank()) +
annotate("text", x = 0, y = 0, size = 15, label = "Micro")
donut
我玩过以下代码:
colour.df$percentage = colour.df$freq / sum(colour.df$freq)* 100
## to this
colour.df$percentage = round(colour.df$freq / sum(colour.df$freq)* 100, digits = 1)
但它会将 ymax 提高到 100.1。将其保留到小数点后 3 位会有所帮助,但不会对重叠部分进行排序。
我也被 geom_label 和 geom_text ggplot2: How to add percentage labels to a donut chart 和 Rounding % Labels on bar chart in ggplot2 撞到了头
总之,长话短说。有什么技巧可以帮助塑造上述 ^ 代码,以便我在圆环图旁边获得圆形百分比标签,而不会重叠?
谢谢
【问题讨论】:
标签: r ggplot2 percentage labels donut-chart