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

如何用Plotly实现与Matplotlib同款的笛卡尔2D平面坐标系?

用Plotly实现类似笛卡尔2D平面坐标系的方案

当然可以用Plotly实现和你提供的Matplotlib版本一致的笛卡尔2D平面坐标系效果,以下是完整实现代码:

import plotly.graph_objects as go
import numpy as np

# 定义坐标系范围
xmin, xmax, ymin, ymax = -9, 9, -9, 9

# 创建空图表(Plotly需要至少一个trace才能渲染坐标系)
fig = go.Figure(data=go.Scatter(x=[], y=[]))

# 更新布局,配置笛卡尔坐标系样式
fig.update_layout(
    width=800,
    height=800,
    # X轴配置
    xaxis=dict(
        range=[xmin - 1, xmax + 1],
        zeroline=True,          # 显示零点轴线
        zerolinewidth=2.5,      # 零点轴线宽度
        showline=True,          # 显示X轴轴线
        linewidth=2.5,          # X轴轴线宽度
        tickmode='array',       # 自定义刻度
        tickvals=np.arange(xmin, xmax + 1),  # 刻度值
        ticktext=[str(i) for i in np.arange(xmin, xmax + 1)],  # 刻度文本
        showgrid=True,          # 显示网格
        gridwidth=1,
        gridcolor='rgba(128,128,128,0.25)',  # 网格颜色及透明度
        ticks='outside',
        title=dict(             # X轴标签位置
            text='x',
            x=1.02,
            y=0,
            font=dict(size=16)
        ),
        showspikes=False,
        mirror=False            # 不显示顶部轴线
    ),
    # Y轴配置
    yaxis=dict(
        range=[ymin - 1, ymax + 1],
        zeroline=True,
        zerolinewidth=2.5,
        showline=True,
        linewidth=2.5,
        tickmode='array',
        tickvals=np.arange(ymin, ymax + 1),
        ticktext=[str(i) for i in np.arange(ymin, ymax + 1)],
        showgrid=True,
        gridwidth=1,
        gridcolor='rgba(128,128,128,0.25)',
        ticks='outside',
        title=dict(
            text='y',
            x=0,
            y=1.02,
            font=dict(size=16)
        ),
        showspikes=False,
        mirror=False            # 不显示右侧轴线
    ),
    plot_bgcolor='white',
    showlegend=False
)

# 显示图表
fig.show()

关键配置说明

  • 利用zeroline将X、Y轴定位在零点位置,通过zerolinewidth设置轴线粗细,对应Matplotlib中spines的位置与宽度设置
  • 通过mirror=False隐藏顶部和右侧的冗余轴线,只保留底部X轴和左侧Y轴
  • 自定义刻度数组覆盖全部整数刻度,同时设置半透明灰色网格线,和Matplotlib版本的视觉效果一致
  • 通过轴标题的x、y参数调整标签位置,实现和Matplotlib中ax.text一致的轴标签摆放效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:45:35