簡體   English   中英

ggplot 將閃避與堆疊條形圖相結合

[英]ggplot combine dodge with stacked barplot

我想在 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)

結果是: 在此處輸入圖像描述

我仍然對兩件事不滿意:我希望日期在兩個欄之間(但這是一個小問題)然后我真的希望對於每個日期,兩個欄都有不同的 colors:對於例如,我想讓左邊的欄為綠色(深綠色和淺綠色),右邊的欄為藍色(深藍色和淺藍色)。 可能嗎?

這至少是主要問題的解決方案。 我建議使用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()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM