如何在 ggplot 中将“填充”变量的条形排列在一起?

问题描述 投票:0回答:1

这是我的代码:

sur %>% 
  select(circumstances_bite, circumstances_bite_broad) %>% 
  drop_na() %>% 
  ggplot(aes(y=fct_infreq(circumstances_bite), fill = circumstances_bite_broad))+
  geom_bar()+
  xlab("No of people")+
  ylab("circumstance of bite")+
  ggtitle ("circumstance of bite by a pet dog")

如何根据填充变量对条形进行分组?一起摸索不同的颜色条,而不是分开摸索。这两个变量都是因素。

my graph

r ggplot2 bar-chart categorical-data
1个回答
0
投票

一个简单的解决方案是在 ggplot 之外手动计算计数,然后按照您想要的顺序对数据进行排序,即按

circumstances_bite_broad
并通过
forecast::fct_inorder
修复顺序。

使用一些虚假的随机示例数据:

set.seed(123)

library(tidyverse)

sur <- data.frame(
  circumstances_bite = sample(LETTERS[1:26], 100, replace = TRUE)
) |>
  mutate(circumstances_bite_broad = case_when(
    circumstances_bite %in% LETTERS[1:9] ~ "a",
    circumstances_bite %in% LETTERS[10:18] ~ "b",
    circumstances_bite %in% LETTERS[19:26] ~ "c"
  ))

sur %>%
  select(circumstances_bite, circumstances_bite_broad) %>%
  drop_na() %>%
  count(circumstances_bite, circumstances_bite_broad) |>
  arrange(circumstances_bite_broad, desc(n)) |>
  mutate(circumstances_bite = fct_inorder(circumstances_bite)) |>
  ggplot(aes(x = n, y = circumstances_bite, fill = circumstances_bite_broad)) +
  geom_col() +
  xlab("No of people") +
  ylab("circumstance of bite") +
  ggtitle("circumstance of bite by a pet dog")

© www.soinside.com 2019 - 2024. All rights reserved.