r - 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 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")
解决方案
由于您尚未提供数据,因此我使用的是默认数据集之一。您可以使用(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 日创建
推荐阅读
- node.js - 问题刷新页面nodejs无法/get错误
- python - 为什么我从 QuantLib 中的不同信用定价引擎得到不同的结果
- kubernetes - 如何允许 Argo 工作流(Kind 集群)工作容器访问主机端口?
- angular - 以角度更改 intl-tel-input 字段宽度
- google-api - Youtube API 是否获得许可?
- tensorflow - 加载多个保存的 tensorflow/keras 模型进行预测
- sql - 雅典娜/普雷斯托 | 自加入时无法匹配 ID 行
- python - 高效切片三角稀疏矩阵
- tsql - SQL server 查询计算后得到结果
- javascript - 尝试将底部栏与响应式侧边栏放在一起