首页 > 解决方案 > 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)

结果是: 在此处输入图像描述

我仍然对两件事不满意:我希望日期在两个条之间(但这是一个小问题)然后我真的希望对于每个日期,两个条具有不同的颜色:例如,我想让左边的栏为绿色(深绿色和浅绿色),右边的栏为蓝色(深蓝色和浅蓝色)。可能吗?

标签: rggplot2bar-chart

解决方案


这至少是主要问题的解决方案。我建议使用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()

在此处输入图像描述


推荐阅读