簡體   English   中英

ggplot分組堆棧欄以顯示比例

[英]ggplot grouped stack bar to show proportion

我有以下格式的數據:

Year    Group    Completed    Sum
2019      A         201        502
2019      B         454        521
2019      C         302        488
2020      A         382        400
2020      B         234        509
2020      C         354        432

我正在嘗試創建一個分組的堆棧條形圖,以顯示各個方面的年份,然后顯示每個組。 我希望條形的高度是 Sum 的值,然后將條形中的堆棧到 go 直到完成的值。

我目前有:

ggplot(df, aes(x = Group, y = Sum, fill = Completed)) +
    geom_bar(position = "stack", stat = "identity") +
    facet_wrap( ~ Year)

這給了我我想要的一切,除了完成不是在每個條上作為堆棧而是根據完成的值對條進行着色。 我怎樣才能改變它,以便完成成為每個條中的堆棧,直到完成的高度?

在繪制它之前,您需要在 df 上做一些工作......

library(tidyverse)

df %>% mutate(Incomplete = Sum - Completed) %>%     #calculate Incomplete
  pivot_longer(c(Completed, Incomplete)) %>%        #convert to long format
  ggplot(aes(x = Group, y = value, fill = name)) +  #fill is Complete or Incomplete
  geom_bar(position = "stack", stat = "identity") +
  facet_wrap( ~ Year)

在此處輸入圖像描述

要將Completed放在每個條的底部,請將aes()語句中的fill = name替換為fill = fct_rev(name) (感謝@utubun 指出這一點)。

像@Andrew Gustar 那樣做起來要容易得多(但我希望Completed從底部開始)。 只需將其視為一種替代解決方法,演示如何使用ggplot::geom_tile()

代碼

library(tidyverse)

dat %>%
  rename_all(tolower) %>%
  mutate(
    y_com = completed / 2,
    y_sum = (completed + sum) / 2
  ) %>%
  pivot_longer(cols = c(y_com, y_sum), values_to = 'y') %>%
  mutate(
    height     = ifelse(name == 'y_com', completed,  sum - completed),
    width      = .75,
    label      = ifelse(name == 'y_com', completed, sum),
    name       = gsub('y_', '', name),
    completed  = NULL,
    sum        = NULL,
  ) %>%
  ggplot(aes(x = group, y = y, height = height, width = width, fill = name, label = label)) +
  geom_tile(show.legend = FALSE) +
  geom_text(aes(y = label), vjust = -.25, colour = 'gray75') +
  scale_fill_brewer(type = 'qual', palette = 'Blues', direction = -1) +
  facet_wrap(~year) +
  labs(
    title   = 'ggplot grouped stack bar to show proportion',
    caption = 'https://stackoverflow.com/q/67607061/1861328',
    x       = 'Group',
    y       = 'Value'
  ) +
  ggthemes::theme_few()

在此處輸入圖像描述

數據

dat <- structure(
  list(
    Year = c(2019L, 2019L, 2019L, 2020L, 2020L, 2020L),
    Group = c("A", "B", "C", "A", "B", "C"),
    Completed = c(201L, 454L, 302L, 382L, 234L, 354L),
    Sum = c(502L, 521L, 488L, 400L, 509L, 432L)
  ),
  class = "data.frame",
  row.names = c(NA,-6L)
)

暫無
暫無

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

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