2012-11-27 56 views
4

我想顯示堆疊欄中的百分比數字。但是,一個組的比例非常低。兩個值彼此重疊。我改爲'postion ='身份證'。它仍然不會工作.....任何想法?如何使用geom_text在堆積條形圖中顯示值?

x4.can.m <- structure(list(canopy = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("0%", "1 to 84%", 
"85% +"), class = "factor"), YearQuarter = structure(c(1L, 1L, 
1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L), .Label = c("2011-09-01", 
"2011-12-01", "2012-03-01", "2012-06-01", "2012-09-01"), class = "factor"), 
    value = c(0.51, 0.01, 0.48, 0.52, 0.01, 0.47, 0.53, 0.01, 
    0.47, 0.57, 0.01, 0.41, 0.61, 0.01, 0.38)), .Names = c("canopy", 
"YearQuarter", "value"), row.names = c(NA, -15L), class = "data.frame") 


x4.can.bar <- ggplot(data=x4.can.m, aes(x=factor(YearQuarter), y=value,fill=canopy)) + geom_bar(stat="identity",position = "stack",ymax=100) 

x4.can.bar+scale_y_continuous(formatter='percent')+ 
labs(y="Percentage",x="Year Quarter") + 
geom_text(aes(label =paste(round(value*100,0),"%",sep="")),size = 3, hjust = 0.5, vjust = 4,position ="identity") 

回答

7

一個解決方案是將棧欄更改爲一個躲閃一個

x4.can.bar <- ggplot(data=x4.can.m, aes(x=factor(YearQuarter), y=value,fill=canopy)) + 
        geom_bar(stat="identity",position = "dodge",ymax=100) + 
      geom_text(aes(label =paste(round(value*100,0),"%",sep=""),ymax=0), 
         position=position_dodge(width=0.9), vjust=-0.25) 
x4.can.bar 

enter image description here

11

您需要爲標籤的放置指定合理的價值觀 - 如果你這樣做外呼叫,這將比在呼叫中嘗試這麼做要容易得多。

您可以通過獲取每個堆疊組件的中點來做到這一點。

使用plyrddply這是一個簡單的服用累計之和減去一半的電流值,我使用ggplot2_0.9.2.1每個YearQuarter

library(plyr) 
x4.can.m <- ddply(x4.can.m, .(YearQuarter), mutate, csum = cumsum(value)-value/2) 

x4.can.bar <- ggplot(data=x4.can.m, aes(x=factor(YearQuarter), y=value,fill=canopy)) + 
geom_bar(stat="identity",position = "stack",ymax=100) 

x4.can.bar + 
scale_y_continuous(expand = c(0,0), labels = percent) + 
labs(y="Percentage",x="Year Quarter")+ 
geom_text(aes(y = csum,label =paste(round(value*100,0),"%",sep="")), 
      size = 3, hjust = 1, vjust = 0) 

注意內,所以formatter不再是scale_y_continuous有效的參數,替換爲label = percent。見this question和相關鏈接

enter image description here

+2

我喜歡你的解決方案。 – agstudy

+0

@mnel,謝謝。什麼是升級到ggplot2_0.9.2.1最簡單的方法。我正在使用R_2.15.1仍然..... –

+0

在新的R會話中運行'install.packages('ggplot2')' – mnel