根据计数而不是类别 (R/Excel) 填充堆积条形图的颜色

Filling colors of a stacked bar chart according to count instead of category (R/Excel)

我想创建一个堆积条形图,但我希望根据计数来决定颜色。例如,如果我有 5 个条形,每个条形有 3 个类别,则条形图的默认着色方式是按类别。 (例如,类别 1 为红色,类别 2 为蓝色,类别 3 为绿色)。但是,我想要的是:如果对于第 1 条,第 1 类的计数最高,那将是红色。同样,如果对于条形图 2,类别 3 的计数最高,我希望第二个条形图的类别 3 为红色。我有什么办法可以做到这一点吗?我可以使用 R/Excel/Numbers/any 其他软件。

这是我目前拥有的,我希望颜色由频率决定(几乎像热图)

这在 R 中很简单。

如果我们有这样的数据:

set.seed(69)
df <- data.frame(category = sample(LETTERS, 200, TRUE))

我们可以做到:

library(ggplot2)

ggplot(df, aes(x = category)) + 
  geom_bar(aes(fill = ..count..), color = "black") +
  scale_fill_gradientn(colours = c("forestgreen", "gold", "red"))


编辑

从OP的补充资料来看,数据好像是这样的:

set.seed(69)
data <- data.frame(Question = rep(LETTERS[1:5], each = 5),
                   Response = rep(c("Strongly disagree", "Disagree", "Neutral",
                                  "Agree", "Strongly agree"), 5),
                   Frequency = as.vector(replicate(5, {
                                x <- sample(10:30, 5, TRUE); x / sum(x)})))

在这种情况下,我们可以这样做:

ggplot(data = data, aes(y = Question, x = Frequency)) + 
  geom_col(aes(fill = Frequency)) +
  geom_text(aes(label = stringr::str_wrap(Response, 10)), 
            position = position_stack(vjust = 0.5)) +
  scale_fill_gradientn(colours = c("forestgreen", "gold", "red"))


编辑

OP 的进一步请求...

ggplot(data = data, aes(y = Question, x = Frequency)) + 
  geom_col(aes(fill = Question, alpha = Frequency)) +
  geom_text(aes(label = stringr::str_wrap(Response, 10)), 
            position = position_stack(vjust = 0.5)) +
  scale_fill_manual(values = c("deepskyblue4", "forestgreen", "gold", 
                                "orange", "red"),
                    name = "Question") +
  scale_alpha_continuous(guide = "none") +
  theme_minimal() +
  theme(panel.grid = element_blank())

reprex package (v0.3.0)

于 2020-08-14 创建