在R中如何用scale_fill_manual()改变条形图的颜色?

5kgi1eie  于 2023-02-01  发布在  其他
关注(0)|答案(2)|浏览(426)

我希望我的条形图与图例相对应,并使用我自己的颜色(而不是默认颜色)对它们进行着色。

# library
library(ggplot2)

# create a dataset
specie <- c(rep("IFNg_WNH", 2) , 
            rep("IFNg_AA", 2), 
            rep("IL1b_WNH", 2), 
            rep("IL1b_AA", 2),
            rep("IL6_WNH", 2), 
            rep("IL6_AA", 2) 
)

condition <- rep(c("down", "up"), 6)

value <- c(452,216,
           348,327,
           207,61,
           75,53,
           177,191,
           379,318)
data <- data.frame(specie,condition,value)

data

# Grouped
p <- ggplot(data, aes(fill=condition, y=value, x=specie)) +
  geom_bar(position="dodge", stat="identity")

z <- p+labs(y = "Number of genes", x = "Cytokines")+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.line=element_line(size=1))+
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))+
  scale_fill_discrete(labels=c('up', 'down'))

z

一旦我加上

z + scale_fill_manual(values=c('#eb4034','#0a0a0a'))

颜色正在改变,但图例恢复到错误的颜色。发生了什么?

muk1a3rh

muk1a3rh1#

type添加到scale_fill_discrete
type:以下选项之一:
·颜色代码的字符向量。
·颜色代码的字符向量列表。
·返回离散颜色/填充比例的函数

ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(position="dodge", stat="identity") + 
  labs(y = "Number of genes", x = "Cytokines") + 
  theme_classic() + 
  theme(plot.title = element_text(hjust = 0.5)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_fill_discrete(labels=c('up', 'down'), type=c('#eb4034','#0a0a0a'))

1rhkuytd

1rhkuytd2#

这里有两个问题。首先,scale_fill_manual()本质上会“覆盖”scale_fill_discrete()。相反,只使用一个包含所有相关参数的scale_fill_*()调用:

library(ggplot2)

p + 
  labs(y = "Number of genes", x = "Cytokines")+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.line=element_line(size=1))+
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))+
  scale_fill_manual(labels = c('up', 'down'), values=c('#eb4034', '#0a0a0a'))

然而,当前labels参数实际上是在重新编码数据,因此"up"值被标记为"down",反之亦然,我认为这不是您想要的。我最好的猜测是,您实际上是在尝试更改标签在图例中显示的顺序。如果是这样,您可以将condition的因子水平更改为您想要的顺序:

data$condition <- factor(data$condition, c("up", "down"))

p <- ggplot(data, aes(fill=condition, y=value, x=specie)) +
  geom_bar(position="dodge", stat="identity")

p + 
  labs(y = "Number of genes", x = "Cytokines")+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.line=element_line(size=1))+
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))+
  scale_fill_manual(values=c('#eb4034', '#0a0a0a'))

相关问题