R ggplot2中geom_point气泡上色及viridis离散配色设置方法
前置准备
如果未安装viridis配色包,先运行以下命令安装:
install.packages("viridis")
完整可运行代码
# 加载所需包 library(ggplot2) library(reshape2) library(viridis) # 示例数据构造,如果你是从本地读取dat.csv,直接替换这段为你的读文件代码即可 dat <- structure(list(station = c(980009L, 980042L, 980145L, 980338L, 980351L, 980365L, 980563L), JAN = c(0.04, 0.04, 0.04, 0.04, 0.04, 0.05, 0), FEB = c(0.05, 0.04, 0.99, 0.99, 0.99, 0.04, 0.99), MAR = c(0.04, 0.99, 0.99, 0.99, 0.99, 0.99, 0), APR = c(0.05, 0.04, 0.99, 0.99, 0.99, 0.99, 0), MAY = c(0.06, 0.05, 0.95, 0.05, 0.96, 0.94, 0.98), JUN = c(0.05, 0.07, 0.04, 0.04, 0.05, 0.04, 0.99), JUL = c(0.05, 0.04, 0, 0.93, 0.92, 0.97, 0), AUG = c(0.04, 0.06, 0.98, 0.98, 0.99, 0.99, 0), SEP = c(0.04, 0.04, 0.98, 0.04, 0.04, 0.04, 0), OCT = c(0.04, 0.07, 0.99, 0.05, 0.04, 0.99, 0), NOV = c(0.04, 0.07, 0.99, 0.05, 0.06, 0.05, 0), DEC = c(0.04, 0.99, 0.05, 0.04, 0.04, 0.05, 0)), class = "data.frame", row.names = c(NA,-7L)) # 数据长宽转换 pcm <- melt(dat, id = c("station")) pcm$station <- factor(pcm$station, levels = unique(pcm$station)) # 百分比计算+切为10个离散分组,对应10种viridis配色 pcm$value_percent <- pcm$value * 100 pcm$value_group <- cut(pcm$value_percent, breaks = seq(0, 100, by = 10), include.lowest = TRUE) # 绘图 p <- ggplot(pcm, aes(x = variable, y = station)) + geom_point(aes(fill = value_group, size = value_percent), alpha = 0.5, shape = 21) + coord_fixed(ratio = 1) + labs(x = "month", y = "station", size = "Percentage") + scale_size_continuous(limits = c(0, 100), breaks = seq(0, 100, by = 10)) + scale_x_discrete(expand = c(0.1, 0)) + # 调用离散viridis配色,调整option参数可切换同系列不同配色风格 scale_fill_viridis_d(option = "D", drop = FALSE) + # 隐藏填充色对应的图例,保留大小图例 guides(fill = "none") # 导出图片 png("Bubble_plot.png", width = 800, height = 600) print(p) dev.off()
调整说明
- 针对问题a:你原本使用的
shape=21本身就支持填充色展示,只需新增guides(fill = "none")语句即可直接隐藏填充色对应的图例,不会影响大小图例的正常显示。 - 针对问题b:先通过
cut()函数把0-100的连续百分比值切为10个等距离散分组,再调用scale_fill_viridis_d()即可匹配10种离散的viridis配色。
内容的提问来源于stack exchange,提问作者Lyndz
相关产品推荐
相关产品推荐

