2016-02-08 248 views
4

我對R很新...所以原諒我。我正在嘗試使用ggplot2製作甜甜圈圖。 我修改了帖子 ggplot Donut chart的代碼,但現在我無法在圖表中添加百分比。 這是我的嘗試:ggplot2:如何將百分比標籤添加到圓環圖

library(ggplot2) 

blank_theme <- theme_minimal()+ 
    theme(
    axis.title.x = element_blank(), 
    axis.title.y = element_blank(), 
    panel.border = element_blank(), 
    panel.grid=element_blank(), 
    axis.ticks = element_blank(), 
    plot.title=element_text(size=14, face="bold") 
) 



dat = data.frame(count=c(319, 442, 239), category=c("University", "High Scool", "Lower")) 


dat$fraction = dat$count/sum(dat$count) 

dat$ymax = cumsum(dat$fraction) 
dat$ymin = c(0, head(dat$ymax, n=-1)) 

dat$category <- factor(dat$category, levels = c("University", "High Scool", "Lower")) 


p1 = ggplot(dat, aes(fill=category, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) + 
    geom_rect(color='blue') + 
    coord_polar(theta="y") + 
    xlim(c(1, 4)) 



edu<-p1 + scale_fill_brewer("Education") + blank_theme + 
    theme(axis.text.x=element_blank()) + theme(legend.position=c(.5, .5)) + ggtitle("") + 
    theme(panel.grid=element_blank()) + 
    theme(axis.text=element_blank()) + 
    theme(axis.ticks=element_blank()) + 
    theme(legend.title = element_text(size=16, face="bold")) + 
    theme(legend.text = element_text(size = 14, face = "bold")) 

edu 

我試過很多geom_text和scale_y_continuous代碼,但什麼都沒有。 有人可以幫我嗎? 感謝

回答

5

你可以使用geom_label

edu + geom_label(aes(label=paste(fraction*100,"%"),x=3.5,y=(ymin+ymax)/2),inherit.aes = TRUE, show.legend = FALSE) 

enter image description here

+0

......並且使標籤大......我試過 「label.size」,但它不工作.. 。 – Giorjet

+0

在'geom_label'中添加'size = 8'或更多(但不在'aes'內) – scoa

+0

我喜歡這張圖。有人知道我可以選擇自己的顏色而不是藍色的顏色嗎? –

相關問題