简体   繁体   中英

ggplot combine dodge with stacked barplot

I would like to combine stacked with dodge style of a barplot in ggplot. I'm quite near it with this code:

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)

which gives as a result: 在此处输入图像描述

I'm still not happy about two things: I would like the date to be between the two bars (but this is a minor problem) and then I really would like to have, for each date, different colors for the two bars: for example I would like to have the left bar to be in a scale of green (dark green and light green) and the right one in a scale of blue (dark blue and light blue). is it possible?

This at least is a solution for the main question. I would suggest to use facet_wrap . Data preparation for this -> bring data in long format, Extract the month name of your date (I use lubridate for this), then plot with 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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM