You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在gnuplot中绘制球坐标系下的彩色矩形?

在Gnuplot中绘制球坐标系下的彩色矩形方案

由于Gnuplot的rect对象不支持直接使用球坐标定义,你可以通过以下几种方式实现需求:

方法1:球坐标转笛卡尔坐标,绘制填充多边形

Gnuplot的polygon对象支持3D笛卡尔坐标,你可以手动将球坐标网格的四个顶点转换为笛卡尔坐标,再逐个绘制填充多边形。

转换公式(适配极角theta+方位角phi的定义)

假设球面半径为R,球坐标转笛卡尔坐标的公式为:

x = R * sin(theta) * cos(phi)
y = R * sin(theta) * sin(phi)
z = R * cos(theta)

示例代码

R = 1.0  # 设定球面半径

# 单个网格单元的球坐标参数
theta0 = 0.2; phi0 = 0.1
theta1 = 0.4; phi1 = 0.3

# 计算四个顶点的笛卡尔坐标
x0 = R*sin(theta0)*cos(phi0); y0 = R*sin(theta0)*sin(phi0); z0 = R*cos(theta0)
x1 = R*sin(theta0)*cos(phi1); y1 = R*sin(theta0)*sin(phi1); z1 = R*cos(theta0)
x2 = R*sin(theta1)*cos(phi1); y2 = R*sin(theta1)*sin(phi1); z2 = R*cos(theta1)
x3 = R*sin(theta1)*cos(phi0); y3 = R*sin(theta1)*sin(phi0); z3 = R*cos(theta1)

# 绘制填充多边形
set obj 1 polygon from x0,y0,z0 to x1,y1,z1 to x2,y2,z2 to x3,y3,z3 fill solid rgb "#ff0000"

# 绘制球面作为背景参考
splot x**2 + y**2 + z**2 = R**2 notitle

方法2:预处理数据,用pm3d批量填充

如果你的网格数量较多,可以将所有网格顶点的笛卡尔坐标整理成pm3d支持的数据格式,利用pm3d的自动填充功能实现批量着色。

数据格式要求

将每个网格的四个顶点按顺序排列,每组顶点间用空行分隔,最后一列标记颜色索引:

x0 y0 z0 1
x1 y1 z1 1
x2 y2 z2 1
x3 y3 z3 1

x4 y4 z4 2
x5 y5 z5 2
x6 y6 z6 2
x7 y7 z7 2

示例命令

set pm3d depthorder  # 处理3D遮挡
set palette defined (1 "#ff0000", 2 "#00ff00", 3 "#0000ff")  # 定义颜色映射
splot "grid_vertices.txt" using 1:2:3:4 with pm3d notitle

方法3:用脚本批量生成多边形对象

针对大量网格,可编写Gnuplot脚本读取网格参数文件,自动循环生成所有填充多边形。

脚本文件plot_spherical_grids.gp

R = 1.0
set style fill solid  # 启用纯色填充
set view 60,30  # 调整视角

# 读取网格参数文件(每行格式:theta0 phi0 theta1 phi1 color_code)
do for [i=1:*] {
    theta0 = NaN; phi0 = NaN; theta1 = NaN; phi1 = NaN; color = ""
    read "grid_params.txt" theta0, phi0, theta1, phi1, color
    if (isnan(theta0)) break  # 读取到文件末尾时退出循环

    # 转换四个顶点坐标
    x0 = R*sin(theta0)*cos(phi0); y0 = R*sin(theta0)*sin(phi0); z0 = R*cos(theta0)
    x1 = R*sin(theta0)*cos(phi1); y1 = R*sin(theta0)*sin(phi1); z1 = R*cos(theta0)
    x2 = R*sin(theta1)*cos(phi1); y2 = R*sin(theta1)*sin(phi1); z2 = R*cos(theta1)
    x3 = R*sin(theta1)*cos(phi0); y3 = R*sin(theta1)*sin(phi0); z3 = R*cos(theta1)

    # 生成多边形对象
    set obj i polygon from x0,y0,z0 to x1,y1,z1 to x2,y2,z2 to x3,y3,z3 fill rgb color
}

# 绘制球面背景
splot x**2 + y**2 + z**2 = R**2 notitle

网格参数文件grid_params.txt示例

0.2 0.1 0.4 0.3 "#ff0000"
0.4 0.1 0.6 0.3 "#00ff00"
0.2 0.3 0.4 0.5 "#0000ff"

内容的提问来源于stack exchange,提问作者vibe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 09:25:14