如何用R ggplot2绘制以count为填充变量的热力图?
问题解决:基于离散count值绘制热力图
原代码问题分析
geom_tile(aes(fill = n))中的n未定义,数据集里无此变量- 重复调用
stat_contour,且原始离散点无法直接生成连续热力填充 stat_density_2d默认基于点密度计算,不能直接映射count值作为填充依据
解决方案:插值生成连续网格后绘图
原始数据是稀疏离散点,要生成以count为填充维度的热力图,需先对count在temperature和relative_humidity_percent的范围内做插值,生成连续网格数据后再绘图。
步骤1:安装并加载必要的包
install.packages(c("ggplot2", "akima")) library(ggplot2) library(akima)
步骤2:对原始数据进行插值
使用akima::interp函数生成连续网格:
# 生成插值后的网格数据 interp_data <- interp(x = templ$temperature, y = templ$relative_humidity_percent, z = templ$count, xo = seq(min(templ$temperature), max(templ$temperature), length=100), yo = seq(min(templ$relative_humidity_percent), max(templ$relative_humidity_percent), length=100)) # 转换为ggplot兼容的data.frame格式 interp_df <- data.frame( temperature = rep(interp_data$x, each = length(interp_data$y)), relative_humidity_percent = rep(interp_data$y, length(interp_data$x)), count = as.vector(interp_data$z) )
步骤3:绘制热力图+等高线
用插值后的连续数据绘制符合预期的热力图,同时叠加等高线:
ggplot(interp_df, aes(x = temperature, y = relative_humidity_percent)) + geom_tile(aes(fill = count)) + # 热力填充层 stat_contour(aes(z = count), color = "white", bins = 10) + # 叠加白色等高线 scale_fill_viridis_c(title = "count") + # 使用易读的viridis配色 labs(x = "Temperature", y = "Relative Humidity (%)") + theme_minimal()
替代方案:count加权的密度热力图
如果不想做插值,可通过stat_density_2d的weight参数让密度计算时考虑count的权重,实现类似效果:
ggplot(templ, aes(x = temperature, y = relative_humidity_percent)) + stat_density_2d(aes(fill = after_stat(level)), geom = "polygon", weight = templ$count) + geom_point(aes(size = count), color = "white") + # 叠加原始数据点 scale_fill_viridis_c(title = "Weighted Density (count-based)") + scale_size_continuous(title = "count") + labs(x = "Temperature", y = "Relative Humidity (%)") + theme_minimal()
内容的提问来源于stack exchange,提问作者doraemon
相关产品推荐
相关产品推荐

