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

Python Plotly如何在contour plot(等高线图)上叠加显示网格线?

Plotly等高线图叠加显示网格线解决方案

核心原因:Plotly 坐标轴网格默认渲染层级在图形 trace 下方,会被等高线图层遮挡,需要手动调整配置。

  • 基础配置步骤
    1. 开启X/Y轴的网格显示开关showgrid=True
    2. 给坐标轴添加核心参数layer='above traces',将网格渲染层级调到所有图形之上
    3. 可自定义网格的颜色、宽度,也可调整等高线透明度提升显示效果
  • 代码示例(Plotly Express 版本)
import plotly.express as px
import numpy as np

# 生成测试数据
x, y = np.meshgrid(np.linspace(0, 10, 100), np.linspace(0, 10, 100))
z = np.sin(x) * np.cos(y)

fig = px.contour(x=x[0,:], y=y[:,0], z=z)

# 配置X轴网格
fig.update_xaxes(
    showgrid=True,
    gridwidth=1,
    gridcolor='white',
    layer='above traces'
)
# 配置Y轴网格
fig.update_yaxes(
    showgrid=True,
    gridwidth=1,
    gridcolor='white',
    layer='above traces'
)

# 可选:调整等高线透明度
fig.update_traces(opacity=0.8)

fig.show()
  • 代码示例(Plotly Graph Objects 版本)
import plotly.graph_objects as go
import numpy as np

x, y = np.meshgrid(np.linspace(0, 10, 100), np.linspace(0, 10, 100))
z = np.sin(x) * np.cos(y)

fig = go.Figure(data = go.Contour(x=x[0,:], y=y[:,0], z=z))

fig.update_layout(
    xaxis = dict(showgrid=True, gridcolor='white', gridwidth=1, layer='above traces'),
    yaxis = dict(showgrid=True, gridcolor='white', gridwidth=1, layer='above traces')
)
fig.update_traces(opacity=0.8)

fig.show()

如果默认网格样式不符合需求,也可以手动添加Scatter trace绘制自定义网格,灵活调整网格的间距、样式

效果示例:
示例效果图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:45:05