2016-07-31 86 views
3

我想要個標籤添加到圓環圖,但在繪製百分比值的明確表示(圓和不重疊)均告失敗ggplot圓環圖個標籤

## 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

反正長話短說。有助於塑造上述^代碼的任何提示,以便我的圓環圖旁邊的四捨五入百分比標籤不重疊?

謝謝

donutchart

回答

6

四捨五入我們可以取代圓形百分比(百分比,2)和重疊,我們可以使用geom_label_repel從ggrepel包

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 

enter image description here

+0

謝謝@thisisrg ggrepel解決了問題 – Beaver