R ggplot结合道奇和堆叠条形图

R ggplot结合道奇和堆叠条形图,r,ggplot2,bar-chart,R,Ggplot2,Bar Chart,我想结合堆叠和道奇风格的条形图在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 <

我想结合堆叠和道奇风格的条形图在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\u 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()
库(lubridate)
结果(单位)
再长一点(
cols=以“值”开头的_,
name_to=“name”,
值\u to=“值”
) %>% 
mutate(dates\u name=parse\u number(as.character(dates\u g)),
日期名称=月份(ymd(日期,标签=真))
ggplot(结果长度,aes(x=名称,y=值,fill=ID))+
几何图形栏(stat='identity',position='stack')+facet\u网格(~dates\u name)+
主题_bw()