r - 将 geom_text 放置在 geom_col 堆叠条形图中每个条形段的中间

标签 r ggplot2 stacked-chart geom-text

这个问题在这里已经有了答案:





Showing data values on stacked bar chart in ggplot2

(2 个回答)


4年前关闭。




我想在 geom_col 中放置相应的值标签每个条形段中间的堆积条形图 .

然而,我天真的尝试失败了。

library(ggplot2) # Version: ggplot2 2.2

dta <- data.frame(group  = c("A","A","A",
                             "B","B","B"),
                  sector = c("x","y","z",
                             "x","y","z"),
                  value  = c(10,20,70,
                             30,20,50))

ggplot(data = dta) +
  geom_col(aes(x = group, y = value, fill = sector)) +
  geom_text(position="stack",
            aes(x = group, y = value, label = value)) 



显然,设置 y=value/2geom_text也无济于事。此外,文本以错误的顺序定位(颠倒)。

任何(优雅的)想法如何解决这个问题?

最佳答案

您需要将变量映射到美学来表示 geom_text 中的组。 .对您来说,这是您的“部门”变量。您可以将它与 group 一起使用美学在 geom_text .

然后使用 position_stackvjust使标签居中。

ggplot(data = dta) +
    geom_col(aes(x = group, y = value, fill = sector)) +
    geom_text(aes(x = group, y = value, label = value, group = sector),
                  position = position_stack(vjust = .5))

您可以通过全局设置您的美学来节省一些输入。然后fill将用作 geom_text 的分组变量你可以跳过 group .
ggplot(data = dta, aes(x = group, y = value, fill = sector)) +
    geom_col() +
    geom_text(aes(label = value),
              position = position_stack(vjust = .5))

enter image description here

关于r - 将 geom_text 放置在 geom_col 堆叠条形图中每个条形段的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40724142/

相关文章:

r - 负指数拟合: curve looks too high

r - 丢失数据时 geom_bar 的宽度一致

javascript - dc.js 按月排序 X 轴

python - 条件工具提示 Bokeh 堆积图

r - 在 Shiny 的应用程序中更改选项卡面板名称的字体

r - 使用 MuMIn r.squaredGLMM 计算泊松 GLMM 的 R 平方

r - 将 n 个 ggplots 排列成下三角矩阵形状

r - 在 ggplotly 中使用 ggplot2 的 sec.axis

python - 如何在堆叠条形图显示中抑制零

r - 如何取消列出 R 嵌套列表中的任意级别?