我正在尝试将百分比标签添加到圆环图表中,但在绘制明确的百分比值表示(圆形而非重叠)方面未能成功
## 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))
所有准备用于绘图。我可能已经这样做了一种特殊的方式,因为我必须为涉及颜色的其他类别制作多个甜甜圈,但我无法理解(facet?)。
## 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&amp; geom_text ggplot2: How to add percentage labels to a donut chart&amp; Rounding % Labels on bar chart in ggplot2
无论如何长话短说。任何提示,以帮助塑造上面的^代码,所以我得到我的甜甜圈图旁边的圆形百分比标签,没有重叠?
谢谢
答案 0 :(得分:11)
对于舍入,我们可以用圆形(百分比,2)替换百分比,对于重叠,我们可以使用ggrepel包中的geom_label_repel
library(ggrepel)
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_repel(aes(label = paste(round(percentage,2),"%"), 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
请注意,ggrepel会产生警告(我也跳过了重新排序颜色级别的步骤,随意纠正/评论):
In min(x) : no non-missing arguments to min; returning Inf
In max(x) : no non-missing arguments to max; returning -Inf