我想在 ggplot2 中的堆积条形图上显示数据值。这是我尝试的代码
library(ggplot2)
Data <- data.frame(
Year = c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4)),
Category = c(rep(c("A", "B", "C", "D"), times = 4)),
Frequency = c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
)
ggplot(Data, aes(Year, Frequency, fill = Category)) +
geom_col() +
geom_text(aes(label = Frequency), size = 3, hjust = 0.5, vjust = 3, position = "stack")
创建于 2023 年 4 月 7 日 reprex v2.0.2
我想在每个部分的中间显示这些数据值。在这方面的任何帮助将受到高度赞赏。谢谢
最佳答案
来自ggplot 2.2.0
通过在 geom_text
中使用 position =position_stack(vjust = 0.5)
可以轻松堆叠标签。
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
另请注意,“position_stack()
和 position_fill()
现在按分组的相反顺序堆叠值,这使得默认堆叠顺序与图例匹配。”
答案对旧版本的ggplot
有效:
这是一种计算条形中点的方法。
library(ggplot2)
library(plyr)
# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year),
transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)
# library(dplyr) ## If using dplyr...
# Data <- group_by(Data,Year) %>%
# mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
geom_bar(aes(fill = Category), stat="identity") +
geom_text(aes(label = Frequency, y = pos), size = 3)
关于r - 在ggplot2中的堆积条形图上显示数据值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6644997/