如何用Gnuplot绘制散点数据密度2D等高线图?修正色条与轴缩放问题
问题描述
基于散点数据绘制2D等高线图时遇到两个问题:
- 散点图的第三列数据已归一化至[0.0, 1.0]范围,但等高线图右侧色条显示范围为[-0.2, 1.0];
- 两张图的XY轴缩放比例不一致,同一数据集应保持相同缩放。
原脚本如下:
### 2D density color plot reset session # create some random rest data set table $Data set samples 700 plot '+' u (invnorm(rand(0))):(invnorm(rand(0))) w table set samples 500 plot '+' u (invnorm(rand(0))+2):(invnorm(rand(0))+2) w table unset table # for each datapoint: how many other datapoints are within radius R R = 0.5 # Radius to check Dist(x0,y0,x1,y1) = sqrt((x1-x0)**2 + (y1-y0)**2) set print $Density do for [i=1:|$Data|] { x0 = real(word($Data[i],1)) y0 = real(word($Data[i],2)) c = 0 stats $Data u (Dist(x0,y0,$1,$2)<=R ? c=c+1 : 0) nooutput d = c / (pi * R**2) # density: points per unit area print sprintf("%g %g %f", x0, y0, d) } set print # Plot normalized z-values set size ratio -1 # same screen units for x and y set palette rgb 33,13,10 stats $Density u 3 nooutput set table $Density_norm plot $Density u 1:2:($3/STATS_max) w table unset table plot $Density_norm u 1:2:3 w p pt 7 lc palette z notitle pause -1 # Plot 2D contours of created data points set dgrid3d 100,100 splines set contour surface set cntrparam levels incremental 0.0, 0.1, 1.0 set view map splot $Density_norm u 1:2:3 with lines lw 2 lc palette nosurface ### end of script
对应的效果图:
- 归一化数据的散点图:

- 同一归一化数据的等高线图:

解决方案
针对两个问题,修正方法如下:
1. 修正色条范围问题
等高线图色条出现负值是因为set dgrid3d splines会对数据进行插值平滑,导致超出原始数据的[0,1]范围。直接添加set cbrange [0:1]命令,强制色条显示范围与归一化数据一致即可。
2. 修正XY轴缩放比例问题
散点图使用plot命令时,set size ratio -1已保证XY轴等比例,但等高线图使用splot命令时,需要额外添加set view equal xyz命令,确保XY轴的缩放比例和散点图保持一致。
修改后的完整脚本
### 2D density color plot reset session # create some random rest data set table $Data set samples 700 plot '+' u (invnorm(rand(0))):(invnorm(rand(0))) w table set samples 500 plot '+' u (invnorm(rand(0))+2):(invnorm(rand(0))+2) w table unset table # for each datapoint: how many other datapoints are within radius R R = 0.5 # Radius to check Dist(x0,y0,x1,y1) = sqrt((x1-x0)**2 + (y1-y0)**2) set print $Density do for [i=1:|$Data|] { x0 = real(word($Data[i],1)) y0 = real(word($Data[i],2)) c = 0 stats $Data u (Dist(x0,y0,$1,$2)<=R ? c=c+1 : 0) nooutput d = c / (pi * R**2) # density: points per unit area print sprintf("%g %g %f", x0, y0, d) } set print # Plot normalized z-values set size ratio -1 # same screen units for x and y set palette rgb 33,13,10 stats $Density u 3 nooutput set table $Density_norm plot $Density u 1:2:($3/STATS_max) w table unset table plot $Density_norm u 1:2:3 w p pt 7 lc palette z notitle pause -1 # Plot 2D contours of created data points set dgrid3d 100,100 splines set contour surface set cntrparam levels incremental 0.0, 0.1, 1.0 set view map set view equal xyz # 保持XY轴缩放比例一致 set cbrange [0:1] # 强制色条范围与归一化数据匹配 splot $Density_norm u 1:2:3 with lines lw 2 lc palette nosurface ### end of script
内容的提问来源于stack exchange,提问作者magfan
相关产品推荐
相关产品推荐

