如何在ggplot2中仅用内置函数将热图图例改为渐变色?
问题描述
我用ggplot2绘制热图,其他部分都正常,但映射fill的syn_count列图例是分段样式。希望仅借助ggplot2内置函数(不加载scales等其他包),将图例改为渐变展示。
原始代码
all <- ggplot(Neu, aes(type, tag, fill = syn_count))+ geom_tile()+ theme(text = element_text(size=8),axis.text.x = element_text(angle = 1, hjust = 1))+ coord_fixed()+ scale_fill_distiller(palette="YlGn")+ labs(title="所有MeMe神经元的输入情况", x="MeMe神经元", y="输入神经元")+ guides(fill=guide_legend(title="突触数量")) all
示例数据
| tag | syn_count | type |
|---|---|---|
| A | 24 | 1 |
| E | 500 | 1 |
| F | 310 | 2 |
| F | 67 | 2 |
| G | 266 | 3 |
| T | 80 | 3 |
| H | 270 | 4 |
字段类型:tag(字符型)、type(字符型)、syn_count(数值型)
解决方法
问题根源是你使用了guide_legend(),它会强制生成离散的分段图例。只需将其替换为ggplot2内置的guide_colorbar(),即可得到渐变样式的图例,修改后的代码如下:
all <- ggplot(Neu, aes(type, tag, fill = syn_count))+ geom_tile()+ theme(text = element_text(size=8), axis.text.x = element_text(angle = 1, hjust = 1))+ coord_fixed()+ scale_fill_distiller(palette="YlGn")+ labs(title="所有MeMe神经元的输入情况", x="MeMe神经元", y="输入神经元")+ guides(fill=guide_colorbar(title="突触数量")) # 关键修改:替换为渐变图例引导器 all
说明
guide_colorbar()是ggplot2原生的渐变图例工具,无需额外加载包,可直接生成连续渐变的颜色条图例scale_fill_distiller本身就是为连续数值映射设计的渐变色阶函数,搭配guide_colorbar后可正确匹配展示渐变效果
内容的提问来源于stack exchange,提问作者Miga
相关产品推荐
相关产品推荐

