r - 将文本标签添加到 R 中的分组条形图
问题描述
我的数据看起来像这样:
structure(list(region1 = structure(c(1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 6L, 6L,
6L, 6L, 7L, 7L, 7L, 7L), .Label = c("Location1", "Location2",
"Location3", "Location4", "Location5", "Location6",
"OTHERS"), class = "factor"), startYear = c(2016, 2017, 2018,
2019, 2016, 2017, 2018, 2019, 2016, 2017, 2018, 2019, 2016, 2017,
2018, 2019, 2016, 2017, 2018, 2019, 2016, 2017, 2018, 2019, 2016,
2017, 2018, 2019), n = c(322L, 697L, 620L, 849L, 832L, 541L,
868L, 687L, 117L, 706L, 613L, 689L, 733L, 445L, 150L, 220L, 936L,
277L, 195L, 751L, 80L, 851L, 38L, 179L, 808L, 635L, 304L, 617L
)), row.names = c(NA, -28L), class = c("data.table", "data.frame"
))
我正在尝试创建一个分组条形图,每个条形上方都有文本标签。方法如下:
# create grouped barchart
ggplot(dataExample, aes(x = startYear, y = n)) +
geom_col(aes(color = as.factor(region1),
fill = as.factor(region1)),
position = position_dodge(0.8), width = 0.7)+
geom_text(aes(startYear, label = n),
position = position_dodge(0.8), width = 0.7)
不幸的是,我无法让我的标签对齐。这是我得到的:
我如何调整位置,使标签在它们应该在的位置?
解决方案
您需要对geom_text
美学进行分组:
ggplot(dataExample, aes(x = startYear, y = n)) +
geom_col(aes(color = as.factor(region1),
fill = as.factor(region1)),
position = position_dodge(0.8))+
geom_text(aes(startYear, label = n, group=as.factor(region1)),
position = position_dodge(0.8))
(请注意,我删除了witdh
导致错误的选项)
推荐阅读
- python - 使用 search_engine_parser 时出现回溯错误
- python - 我的 django rest 框架 api 中的 update_or_create 工作错误
- r - 如何并行points2network(shp2graph中的函数)R?
- javascript - 如何在函数外部获取具有函数作用域的变量的值,即使用全局作用域中的值?
- javascript - 以编程方式向 SVG 元素添加阴影
- c# - 如何使用 C# 在谷歌云注册表中添加设备?
- arduino - 在 Erlang 中是否可以在 Windows 中使用 open_port?
- python - 以不同方式添加惩罚或加权值
- python - 如何获得针对同一模型的多个外键?(AmbiguousForeignKeysError)
- xml - 基于其他属性在 bash 脚本中提取 XML 属性