Gnuplot多顶点多边形分组着色问题:脚本仅支持2个及以下顶点
问题描述
在gnuplot中为每个含多个顶点的多边形设置不同颜色。数据文件示例如下:
6.185000 8.219000 6.566000 4.724000 1.392000 7.538000 6.185000 8.219000 8.455000 5.243000 1.776000 5.401000 1.515000 5.455000 8.455000 5.243000
当前使用的script.gpl脚本如下:
set style line 1 \ linecolor rgb '#0060ad' \ linetype 1 linewidth 2 \ pointtype 7 pointsize 1.5 set style line 2 \ linecolor rgb '#dd181f' \ linetype 1 linewidth 2 \ pointtype 5 pointsize 1.5 set datafile separator "\t" plot 'path\data.txt' index 0 with linespoints linestyle 1, \ '' index 1 with linespoints linestyle 2
问题:上述脚本仅在每个多边形包含2个及以下顶点时有效,当顶点数超过2个时,会出现警告warning: Skipping data file with no valid points。
问题原因
警告出现的核心原因是gnuplot的index指令对数据集的识别逻辑:它依赖纯空白行分隔不同数据集,若数据中存在格式异常(比如空白行含隐形字符)、或闭合多边形的重复顶点导致数据集边界误判,就会被判定为“无有效点”。此外,linespoints虽能绘制连线和顶点,但针对多边形场景的适配性需要配合更准确的数据集遍历方式。
修复方案
以下两种方案均可解决问题,同时实现每个多边形的差异化颜色设置:
方案1:循环遍历数据集(适配多多边形场景)
如果后续需要处理更多多边形,用循环遍历更高效:
# 定义不同多边形的样式 set style line 1 linecolor rgb '#0060ad' linetype 1 linewidth 2 pointtype 7 pointsize 1.5 set style line 2 linecolor rgb '#dd181f' linetype 1 linewidth 2 pointtype 5 pointsize 1.5 set datafile separator "\t" # 遍历所有空白行分隔的数据集,索引从0开始 plot for [i=0:1] 'path/data.txt' index i with linespoints linestyle (i+1) title sprintf("Polygon %d", i+1)
注意:Windows路径建议用正斜杠/或双反斜杠\\,避免转义冲突
方案2:指定数据集行范围(适配少量多边形场景)
如果仅需处理2个多边形,可直接指定每个多边形的行索引范围,规避index的识别问题:
set style line 1 linecolor rgb '#0060ad' linetype 1 linewidth 2 pointtype 7 pointsize 1.5 set style line 2 linecolor rgb '#dd181f' linetype 1 linewidth 2 pointtype 5 pointsize 1.5 set datafile separator "\t" # 第一个多边形:第0-3行;第二个多边形:第5-8行(跳过中间空白行) plot 'path/data.txt' every ::0::3 with linespoints linestyle 1, \ '' every ::5::8 with linespoints linestyle 2
可选优化:绘制填充多边形
若需要为多边形添加填充色,将linespoints替换为filledcurves closed即可,还可通过fillalpha设置透明度:
plot for [i=0:1] 'path/data.txt' index i with filledcurves closed linestyle (i+1) fillalpha 0.3 title sprintf("Polygon %d", i+1)
关键注意事项
- 确保数据文件中的分隔空白行是纯空行(无空格、制表符等隐形字符),否则gnuplot无法正确识别数据集边界。
- 若使用Windows系统,路径中的反斜杠需转义为
\\,或直接替换为正斜杠/。
内容的提问来源于stack exchange,提问作者ilias pr0
相关产品推荐
相关产品推荐

