r - 如何使用 geom_text 在堆积条形图中显示值?

标签 r ggplot2

我想在堆叠栏中显示百分比数字。但是,有一组的比例非常低。两个值相互重叠。我更改为“位置 = 身份”。它仍然行不通.....有什么想法吗?

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")

最佳答案

您需要为标签的放置指定合理的值 - 如果您在 ggplot 之外执行此操作调用,这比在调用中尝试这样做要容易得多。

您可以通过取每个堆叠组件的中点来做到这一点。

使用 plyrddply这是一个简单的方法,即在每个 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)

请注意,我正在使用 ggplot2_0.9.2.1 ,所以 formatter不再是 scale_y_continuous 的有效参数,替换为 label = percent .见 this question和相关链接

enter image description here

关于r - 如何使用 geom_text 在堆积条形图中显示值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13576139/

相关文章:

r - 库错误(ggplot2): There is no package called 'ggplot2'

r - 在 R 中使用 ggplot2 绘制地铁图

sql - 从 Postgresql 表中绘制表和关系

R-boxplot 设置为 2 个小数位

r - 在 RCommander 中使用 ggplot2

r - 如何将 ggplot 直方图 x 轴间隔映射到固定调色板?

r - 如何从ggplotly图中删除选项栏?

r - 如何在 ggplot 管道中使用子集?

r - 传说并没有深入到底部

替换 R 中现有矩阵中的随机值