首页 > 解决方案 > Labels on stacked bar chart

问题描述

I've looked at lots of questions on this but nothing seems to get it quite right.

I have this bar chart of soccer matches that's stacked to show which team had better or worse form and how that mapped to the result.

I want to add a label to each of the segments of the bars to show the total for that segment -- eg, 15 for "Blades and draw" -- and also a total for the bar at the top, ideally.

Here's the chart: enter image description here

Here's the code used to create it:

ggplot(Sheff_derby_form_league, aes(x = Result)) + 
geom_bar(aes(y = ..count.., fill = Res_vs_f_team)) +
labs(title = "Blades vs Owls. League derby form and result",
   subtitle = "Team with form advantage a little more likely to win", 
   x = "Better form: > 0.33ppg over opponent. Even form: < 0.33ppg", y = "") 
   + scale_fill_brewer(palette = "RdBu")

标签: rggplot2

解决方案


由于您尚未提供数据,因此我使用的是默认数据集之一。您可以使用(https://indrajeetpatil.github.io/ggstatsplot/reference/ggbarstats.htmlggbarstats )中的函数轻松制作带标签的堆叠条形图,该函数还提供了一些其他有用的细节。正如下面的多个示例所示,可以根据自己的喜好修改默认值。ggstatsplot

# setup
set.seed(123)
library(ggplot2)
library(ggstatsplot)

# percentage
ggstatsplot::ggbarstats(
  data = mtcars,
  main = am,
  condition = cyl,
  messages = FALSE
)

# count
ggstatsplot::ggbarstats(
  data = mtcars,
  main = am,
  condition = cyl,
  data.label = "count",
  package = "wesanderson",
  palette = "Royal2",
  messages = FALSE
)

# count and percentage
ggstatsplot::ggbarstats(
  data = mtcars,
  main = am,
  condition = cyl,
  data.label = "both",
  messages = FALSE
) +
  ggplot2::labs(subtitle = NULL)

reprex 包(v0.2.1)于 2019 年 2 月 13 日创建


推荐阅读