如何用gnuplot将表格数据集转为2D密度分布图?解决相关报错
问题描述
- 作为gnuplot新手,想用单空格分隔的表格数据生成2D密度分布图(展示位置数量分布),已能画出基础x-y散点图,但参考方案时遇到两个报错:
All points x value undefinedTabular output of this 3D plot style not implemented
- 预期效果为带等高线+颜色填充的密度图形式
- 数据集说明:
- 列对应关系:
X(1000)是x坐标,Y(1000)是y坐标,ametype是位置类型,amename是位置ID - 数据示例:
ametype amename X(1000) Y(1000) km-to-carpark Scuba SCUB1 10.72 49.01 Scuba SCUB2 13.88 47.32 Scuba SCUB3 14.58 46.46 ... RESTAURANT RESTAU2 76.15 54.34
- 列对应关系:
- 尝试的代码:
set view map set contour set isosample 250, 250 set cntrparam level incremental 1, 0.1 set palette rgbformulae 33,13,10 splot 'data.dat' with lines nosurface #splot for [col=1:10] ‘data.dat’ u ($1):(column(col) > 2 ? 1/0 : column(col)):3
错误原因分析
All points x value undefined:
代码中splot 'data.dat' with lines nosurface未指定数据列,gnuplot默认将第一列作为x值,但你的第一列是字符串类型的位置类型,无法转换为数值坐标,导致所有x值无效。Tabular output of this 3D plot style not implemented:
你使用的with lines + nosurface组合属于不支持表格输出的3D绘图样式,且你的数据是离散散点,并非网格数据,直接用splot画线条也不符合密度图的生成逻辑。
正确实现方法
gnuplot生成2D密度图需要先对散点数据做密度估计,以下两种方法适合新手:
方法1:内置核密度估计(快速生成)
# 输出设置(可根据需求调整终端和尺寸) set terminal pngcairo enhanced font 'Arial,10' size 800,600 set output 'density_plot.png' # 绘图样式配置 set view map # 转为2D视图 set contour base # 等高线在底层显示 set cntrparam levels auto 10 # 自动生成10条等高线 set palette rgbformulae 33,13,10 # 配色方案 set style fill solid 0.5 # 填充半透明 # 生成密度图,指定x为第3列(X(1000)),y为第4列(Y(1000)) splot 'data.dat' using 3:4 smooth kdensity with pm3d, \ '' using 3:4 with points pt 7 ps 0.5 lc 'black' # 可选:叠加原始散点
方法2:网格计数法(自定义密度精度)
适合需要手动控制网格大小的场景:
# 输出设置 set terminal pngcairo enhanced font 'Arial,10' size 800,600 set output 'density_grid.png' # 设置数据范围(根据你的实际数据调整) set xrange [0:100] set yrange [0:60] # 定义网格步长 binwidth_x = 1 binwidth_y = 1 # 统计每个网格内的点数量,输出到临时文件 set table 'density_data.tmp' plot 'data.dat' using (binwidth_x*floor($3/binwidth_x)+binwidth_x/2):\ (binwidth_y*floor($4/binwidth_y)+binwidth_y/2):\ (1) smooth freq unset table # 绘制热力图+等高线 set view map set contour set cntrparam levels auto 8 set palette rgbformulae 33,13,10 splot 'density_data.tmp' using 1:2:3 with pm3d, \ '' using 1:2:3 with lines lw 1 lc 'white'
关键注意事项
- 必须明确指定数据列:
using 3:4对应你的X(1000)和Y(1000)列,不能依赖默认列 - 调整
xrange/yrange要匹配实际数据范围,避免截断有效点 smooth kdensity是gnuplot内置的快速密度估算工具,适合新手快速出图
内容的提问来源于stack exchange,提问作者bonCodigo
相关产品推荐
相关产品推荐

