如何消除ggplot2中density2d绘图的竖线网格效果?
解决2D密度图/分箱图的竖线网格问题
问题根源
竖线网格是因为你的x(小时)和y(年龄)都是离散整数型数据,但绘图函数默认按连续值处理,插值或分箱时在整数边界产生了密度/频数的突变,最终呈现为竖线。以下是针对性的解决方法:
方法1:匹配离散数据的分辨率(stat_density_2d专属)
给stat_density_2d指定n参数,让栅格数量完全匹配x和y的离散取值个数(x有24个值:0-23,y有101个值:0-100),消除插值带来的边界突变:
ggplot(Joined_Data, aes(x=hora, y=edad) ) + stat_density_2d(aes(fill = after_stat(density)), geom = "raster", contour = FALSE, n = c(24, 101)) + # 对应x、y的离散取值数量 scale_x_continuous(breaks = 0:23) + scale_y_continuous(breaks = seq(0, 100, 10)) + scale_fill_continuous(type = "viridis") + theme(legend.position='none')
方法2:给离散数据加微小偏移
通过给x、y值添加极小的随机噪声,让数据不再严格落在整数点上,平滑插值过程:
ggplot(Joined_Data, aes(x=hora + runif(nrow(Joined_Data), -0.4, 0.4), y=edad + runif(nrow(Joined_Data), -0.4, 0.4)) ) + stat_density_2d(aes(fill = after_stat(density)), geom = "raster", contour = FALSE) + scale_x_continuous(breaks = 0:23) + scale_y_continuous(breaks = seq(0, 100, 10)) + scale_fill_continuous(type = "viridis") + theme(legend.position='none')
方法3:调整分箱参数(geom_bin2d/geom_hex专属)
针对geom_bin2d
指定bins参数匹配x、y的离散范围,每个bin对应一个整数组合:
ggplot(Joined_Data, aes(x=hora, y=edad)) + geom_bin2d(bins = c(24, 101)) + # 对应x、y的离散取值数量 scale_fill_continuous(type = "viridis") + theme(legend.position='none')
针对geom_hex
设置binwidth为1(匹配整数单位),让六边形分箱贴合数据分布:
ggplot(Joined_Data, aes(x=hora, y=edad)) + geom_hex(binwidth = c(1, 1)) + # 每个bin宽度对应1个整数单位 scale_fill_continuous(type = "viridis") + theme(legend.position='none')
方法4:提前聚合数据,用geom_tile绘制
先统计每个(x,y)组合的密度/频数,直接用瓦片图绘制,完全避免插值问题:
library(dplyr) # 先聚合数据 agg_data <- Joined_Data %>% count(hora, edad, name = "density") %>% mutate(density = density / sum(density)) # 转换为密度值 # 绘制瓦片图 ggplot(agg_data, aes(x=hora, y=edad, fill=density)) + geom_tile() + scale_fill_continuous(type = "viridis") + theme(legend.position='none')
内容的提问来源于stack exchange,提问作者Kaikus
相关产品推荐
相关产品推荐

