r - ggplot2 标签不会与 geom_col 条一起闪避
问题描述
我已经解决了相关问题,但这些答案并没有解决我的标签不躲避以匹配geom_col
条形的问题:
数据
x <- structure(
list(capacity = c(0, 0, 0, 2.1, 3.1, 4, 4.6, 5.6, 6,
1.9, 2.3, 3.8),
year = c("FY21", "FY21", "FY21", "FY21", "FY21",
"FY20", "FY20", "FY20", "FY20", "FY19", "FY19", "FY19"),
unified_date = structure(c(18536, 18567, 18597, 18628, 18659,
18567, 18597, 18628, 18659, 18536,
18567, 18597), class = "Date")),
row.names = c(NA, -12L), class = c("tbl_df", "tbl", "data.frame"))
代码
ggplot2::ggplot(x, aes(x = unified_date, y = capacity, fill = year)) +
geom_col(position = "dodge") +
geom_text(aes(label = capacity),
position = position_dodge(width = 1),
vjust = -0.5, size = 4)
图表
我已经尝试添加fill = year
到geom_text
aes
, 或group = year
, 移动aes
值,变体position_dodge()
- 没有。
解决方案
试试这个:
#Code
ggplot2::ggplot(x, aes(x = factor(unified_date), y = capacity, fill = year)) +
geom_bar(stat='identity',position = "dodge") +
geom_text(aes(label = capacity),
position=position_dodge(width=0.9), size = 4,vjust=-0.5)+
xlab('Date')
输出:
如果您想正确处理月份,请尝试以下操作:
#Code 2
x %>% mutate(Month=format(unified_date,'%b')) %>%
mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
ggplot2::ggplot(aes(x = Month, y = capacity, fill = year)) +
geom_bar(stat='identity',position = "dodge") +
geom_text(aes(label = capacity),
position=position_dodge(width=0.9), size = 4,vjust=-0.5)+
xlab('Date')
输出:
推荐阅读
- list - 在 Dart 中打印不带括号的列表
- r - 无法使用新更新在 R 中安装 swirl。版本 3.6.2
- angular - 如何使用 Angular 7 从 java REST API 获取数据?
- java - 为什么 RocketMQ DefaultMQProcuderImpl 调用 updateFaultItem 即使消息发送成功
- azure - 请求的内容不存在部署为带有 CDN 和 V-Net 的 Azure Blob 静态网站的 SPA
- angular - 发生未处理的异常:对象原型可能只是一个对象或 null:未定义(角度 8)
- amazon-web-services - 无法成长,因为没有剩余空间
- c# - 如何在 c#.net 项目中检索共享点列表数据
- yugabyte-db - YugabyteDB Postgis 未安装
- sql - 如果没有行返回其他表的连接条件值,则选择默认行