如何用stat_summary_2d生成平滑的二维统计图?
问题描述
我有如下样本数据集:
templ = data.frame(count = c(200,225,610,233,250,210,290,255,279,250), temperature = c(12.2,11.6,12,8.5,4,8.2,9.2,10.6,10.8,10.9), relative_humidity_percent = c(74,78,72,65,77,84,83,74,73,75))
使用stat_summary_2d生成了块状热力图:
ggplot(templ, aes(temperature, relative_humidity_percent, z = count)) + stat_summary_2d(bins = 5) + viridis::scale_fill_viridis() + theme_classic()+ theme(panel.background = element_rect(fill = "black"))
我希望生成平滑渐变的热力图,请问是否可以通过stat_summary_2d实现这类效果?
解答
stat_summary_2d无法实现平滑渐变的热力图效果,因为它的核心逻辑是将平面划分为离散的矩形分箱,对每个分箱内的数据计算统计量(如均值、总和),最终输出的是块状离散的可视化结果,本身不包含插值平滑的逻辑。
要生成类似的平滑热力图,推荐以下几种替代方案:
1. 插值后绘制栅格图
借助akima包对原始数据进行双线性插值,生成连续的网格数据后,用geom_raster绘制平滑热力图:
library(ggplot2) library(akima) # 生成高密度插值网格 interp_result <- interp(x = templ$temperature, y = templ$relative_humidity_percent, z = templ$count, nx = 100, ny = 100) # nx/ny数值越大,平滑度越高 # 转换为数据框格式 interp_df <- data.frame( expand.grid(temperature = interp_result$x, relative_humidity_percent = interp_result$y), count = c(interp_result$z) ) # 绘制平滑热力图 ggplot(interp_df, aes(temperature, relative_humidity_percent, fill = count)) + geom_raster(interpolate = TRUE) + viridis::scale_fill_viridis(na.value = "black") + theme_classic() + theme(panel.background = element_rect(fill = "black"))
2. 基于密度的平滑填充
如果希望基于数据点的密度进行平滑展示,可以使用stat_density_2d的填充模式:
ggplot(templ, aes(temperature, relative_humidity_percent, z = count)) + stat_density_2d(aes(fill = stat(density)), geom = "polygon", contour = TRUE) + viridis::scale_fill_viridis() + theme_classic() + theme(panel.background = element_rect(fill = "black"))
3. 平滑等高线填充图
结合插值后的网格数据,使用geom_contour_filled绘制带平滑填充的等高线图:
ggplot(interp_df, aes(temperature, relative_humidity_percent, z = count)) + geom_contour_filled(bins = 10) + viridis::scale_fill_viridis(discrete = TRUE) + theme_classic() + theme(panel.background = element_rect(fill = "black"))
内容的提问来源于stack exchange,提问作者doraemon
相关产品推荐
相关产品推荐

