如何在R中用scale_fill_manual()修改条形图颜色?图例异常问题
问题描述
我想用ggplot2绘制分组条形图,希望图例使用自定义标签'up'和'down',同时用指定颜色替换默认配色。我先通过scale_fill_discrete设置了图例标签,但添加scale_fill_manual(values=c('#eb4034','#0a0a0a'))修改颜色后,颜色确实生效了,但图例标签却变回了原始的错误状态,这是怎么回事?
原代码如下:
# 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) # 绘制分组条形图 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'))
原因与解决方法
这是因为scale_fill_discrete和scale_fill_manual都是用来设置fill美学属性的比例尺,ggplot2中后添加的比例尺会完全覆盖之前的设置——包括你在scale_fill_discrete里定义的图例标签。
解决方法很简单,把图例标签和自定义颜色放在同一个比例尺设置里即可,以下是两种可行方案:
方法1:合并设置到scale_fill_manual
直接在scale_fill_manual中同时指定颜色和图例标签,替代之前的scale_fill_discrete:
library(ggplot2) # 数据集部分不变 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) # 绘图并同时设置颜色和图例标签 p <- 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))+ 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'), labels=c('up', 'down')) p
方法2:提前设置因子水平(更规范)
先将condition转换为因子并指定显示标签,后续绘图时只需设置颜色即可,避免重复配置:
library(ggplot2) # 数据集处理:把condition转为因子,指定水平和显示标签 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 <- factor(rep(c("down", "up"), 6), levels = c("down", "up"), labels = c('up', 'down')) value <- c(452,216, 348,327, 207,61, 75,53, 177,191, 379,318) data <- data.frame(specie,condition,value) # 绘图时仅需设置自定义颜色 p <- 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))+ 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')) p
内容的提问来源于stack exchange,提问作者Lara
相关产品推荐
相关产品推荐

