如何使用带有两组因子变量的ggplot填充?

时间:2019-09-04 20:24:54

标签: r ggplot2 fill geom-bar

我正在绘制堆积的条形图。例如:

library(data.table)
library(ggplot2)

dt <- data.table(category = c("A", "B", "C", "D", "A", "B", "C", "D"),
             variable = c("X", "X", "X", "X", "Y", "Y", "Y", "Y"),
             value = c(7, 5, 4, 2, 1, 1, 2, 1))
dt$variable <- factor(dt$variable, levels = c("Y", "X"))


p <- ggplot(dt, aes(x=category, y=value, fill=category)) +
  geom_bar(stat="identity", colour = "black") +
  coord_flip() +
  scale_fill_brewer(palette="Set3") +
  theme_bw() +
  theme(
legend.position = "none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.margin=unit(c(0.8,0.8,0.8,0.8),"cm"),
text = element_text(size=14)
  )
p

我正在尝试使变量为“ A”的每个类别都具有不同的颜色,而所有条带中的“ B”中的变量均为黑色。有谁知道如何做到这一点?有没有办法对类别和变量使用填充?

我尝试过:

dt$col <- ifelse(dt$variable == "Y", "black", dt$category)
dt$col <- factor(dt$col, levels = c("black","A", "B", "C", "D"))

p <- ggplot(dt, aes(x=category, y=value, fill=col)) +
  geom_bar(stat="identity", colour = "black") +
  coord_flip() +
  scale_fill_brewer(palette="Set3") +
  theme_bw() +
  theme(
legend.position = "none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.margin=unit(c(0.8,0.8,0.8,0.8),"cm"),
text = element_text(size=14)
  )
p

但是,我似乎无法使用scale_fill_brewer()并将颜色设置为黑色。

1 个答案:

答案 0 :(得分:0)

我认为您第二次尝试的方向正确。最好按照您的方式创建新列col

然后,诀窍是制作一个自定义的色标和颜色图,将颜色值“ black”显式映射为颜色“ black”。然后可以将此自定义颜色映射输入到scale_fill_manual中。

这看起来像您想要的结果吗?

library(data.table)
library(ggplot2)
library(RColorBrewer)

dt <- data.table(category = c("A", "B", "C", "D", "A", "B", "C", "D"),
                 variable = c("X", "X", "X", "X", "Y", "Y", "Y", "Y"),
                 value = c(7, 5, 4, 2, 1, 1, 2, 1))
dt$variable <- factor(dt$variable, levels = c("Y", "X"))

all_levels <- c(unique(dt$category), "black")
dt$col <- ifelse(dt$variable == "Y", "black", dt$category)
dt$col <- factor(dt$col, levels = all_levels)

color_scale <- c(
  brewer.pal(length(all_levels) - 1, name = "Set3"),
  "black"
)
color_map <- setNames(color_scale, all_levels)

ggplot(dt, aes(x=category, y=value, fill=col)) +
  geom_bar(stat="identity", colour = "black") +
  scale_fill_manual(values = color_map) +
  theme_bw() +
  theme(
    legend.position = "none",
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    plot.margin=unit(c(0.8,0.8,0.8,0.8),"cm"),
    text = element_text(size=14)
  )

reprex package(v0.3.0)于2019-09-04创建