r - ggplot 将闪避与堆叠条形图相结合
问题描述
我想在 ggplot 中将堆叠和条形图的闪避样式结合起来。我很接近这个代码:
dates_g <- as.Date(c("2020-03-30","2020-03-30", "2020-04-30","2020-04-30", "2020-05-30","2020-05-30"))
value_x <- c(1, 2, 4, 1.4, 3.2, 1.3)
value_y <- c(1.2, 3, 4.6, 1, 3, 1)
ID <- c("A", "B", "A", "B", "A", "B")
results <- data.frame(dates_g, value_x, value_y, ID)
barwidth = 13
bar_comparison <- ggplot() +
geom_bar(data = results[,c(1,2,4)],
mapping = aes(x=dates_g , y=value_x, fill=ID),
stat ="identity",
position = "stack",
width = barwidth) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
geom_bar(data = results[,c(1,3,4)],
mapping = aes(x=dates_g + barwidth + 0.01 , y=value_y, fill=ID),
stat ="identity",
position = "stack",
width = barwidth) +
xlab("Date") + ylab("Value (in millions)")
ggplotly(bar_comparison)
我仍然对两件事不满意:我希望日期在两个条之间(但这是一个小问题)然后我真的希望对于每个日期,两个条具有不同的颜色:例如,我想让左边的栏为绿色(深绿色和浅绿色),右边的栏为蓝色(深蓝色和浅蓝色)。可能吗?
解决方案
这至少是主要问题的解决方案。我建议使用facet_wrap
. 为此的数据准备 - >以长格式引入数据,提取日期的月份名称(我lubridate
用于此),然后绘制ggplot
library(lubridate)
results_long <- results %>%
pivot_longer(
cols = starts_with("value"),
names_to = "Names",
values_to = "Values"
) %>%
mutate(dates_name = parse_number(as.character(dates_g)),
dates_name = month(ymd(dates_g), label = TRUE))
ggplot(results_long, aes(x = Names, y = Values, fill = ID)) +
geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ dates_name) +
theme_bw()
推荐阅读
- reactjs - 如何允许用户保存输入以供进一步审查
- typescript - 使用 TypeORM 和带有文件夹路径的 Typescript 时出错
- c++ - 如何从指针的指针向量中获取指针值?
- tensorflow - 如何为时间序列异常检测提供这个 LSTM-AE?
- javascript - PostMan 将 JSON post 请求中的空正文发送到 Express 服务器
- python - 如何保护我的 ren'py 项目不被复制?
- clickhouse - clickhouse 是否提供任何工具,例如 red gate sql toolbelt
- linux - 在 apache 配置中未显示预期输出
- node.js - 为什么我不能将 @bundled-es-modules/chai 别名为 chai?
- python - 在 Matplotlib 中同时使用 blitting 为一个子图设置动画,而在 Matplotlib 中通过重绘为另一个子图设置动画