r - 在ggplot2中的堆积条形图上显示数据值

标签 r ggplot2 bar-chart stacked-bar-chart

我想在 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))

enter image description here

另请注意,“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)

Resultant chart

关于r - 在ggplot2中的堆积条形图上显示数据值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6644997/

相关文章:

r - 预测 v7 和 ggplot2 图形将拟合线添加到自动绘图

javascript - 想要在 Google Chart 的条形图中的注释文本上添加顶部填充(可视化)

r - ggplot2 两侧带有正标签的双向条形图

r - 如何获得谷歌搜索结果

R在数据框中的两列之间随机交换值

r - 使用 dplyr 将行添加到分组数据中?

r - 当我的 x 轴是一个因素时,如何手动添加 geom_vline() ? R 格图

r - 渲染 Shiny 页面时出现数据表问题 <DataTables warning : table id=DataTables_Table_0 - Requested unknown parameter>

r - 加载插入符号包时出现错误 : Package "ggplot2" could not be found,

python - 如何在 python 中使用 Plotly 离线模式绘制条形图?