如何修改ggplot2连续气泡图的气泡填充颜色(Viridis调色板)
问题描述
我想修改气泡图的气泡颜色,现有ggplot2绘图代码如下:
ggplot(sum_length, aes(x=vb_width, y=slope, size = length)) + geom_point(alpha=0.5)+ theme_classic() + ylab("Slope category (%)") + xlab("Valley bottom width (m)") + scale_y_discrete(labels= slopebins)+ scale_size(range = c(.1, 12), name="Amount of occupied habitat (km)")
希望气泡颜色随连续型的length变量变化,且使用Viridis调色板。此前找到的方案针对离散数据,不适用我的连续数据。
数据如下:
slope vb_width MU length 1 1to3 <35m 21 26.0568635 2 3to10 <35m 21 133.8732929 3 gt10 <35m 21 49.9302440 4 lt1 <35m 21 13.6335112 5 1to3 >285-427 21 9.5806268 6 3to10 >285-427 21 0.3888544 7 gt10 >285-427 21 0.0000000 8 lt1 >285-427 21 24.3259779 9 1to3 >35-70 21 66.0737107 10 3to10 >35-70 21 140.3568265 11 gt10 >35-70 21 23.9712848 12 lt1 >35-70 21 42.4018746 13 1to3 >427 21 9.0315019 14 3to10 >427 21 0.3993908 15 gt10 >427 21 0.0000000 16 lt1 >427 21 163.8209682 17 1to3 >70-285 21 72.3702302 18 3to10 >70-285 21 38.4964008 19 gt10 >70-285 21 7.9305055 20 lt1 >70-285 21 85.7479024
解决方案
只需对原代码做两处修改即可实现需求:
- 在
aes()中添加color = length,将气泡颜色映射到连续型的length变量 - 添加
scale_color_viridis_c()函数(后缀_c代表对应连续数据),应用Viridis调色板
修改后的完整代码:
ggplot(sum_length, aes(x=vb_width, y=slope, size = length, color = length)) + geom_point(alpha=0.5)+ theme_classic() + ylab("Slope category (%)") + xlab("Valley bottom width (m)") + scale_y_discrete(labels= slopebins)+ scale_size(range = c(.1, 12), name="Amount of occupied habitat (km)") + scale_color_viridis_c(name="Amount of occupied habitat (km)", option = "plasma")
关键说明:
scale_color_viridis_c()是专门为连续型数据设计的Viridis调色板映射函数,默认使用viridis主调色板,可通过option参数切换magma、plasma、inferno、cividis等子调色板- 可以统一颜色和大小图例的标题,让图表逻辑更清晰
- 保留原代码的
alpha=0.5参数,避免气泡重叠时遮挡关键信息
内容的提问来源于stack exchange,提问作者vermicellion
相关产品推荐
相关产品推荐

