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

Plotly 3D散点图显示裁切、立方体坐标轴比例调整问题求解

Plotly 3D散点图显示问题修复方案

两个问题分别对应以下配置调整:

1. 首次加载内容被裁切问题

默认配置下Plotly 3D场景边距预留不足,会出现刻度、标签、散点被边缘裁切的情况,添加两个配置即可修复:

  • 在布局配置中设置全局边距,仅给标题预留顶部空间,其余方向边距设为10px左右的小值避免空间浪费
  • 给三个坐标轴开启automargin=True自动留边属性,避免轴标签、刻度文字被画布边缘裁切

2. 正立方体显示问题

Plotly 3D场景默认会根据画布比例拉伸坐标轴,不会自动按轴范围等比例渲染,只需在场景配置中添加aspectmode='cube'参数,即可强制三个坐标轴按等边长渲染,和matplotlib的立方体3D图效果一致,不受各轴数值范围跨度差异影响。


修改后完整代码

import pandas as pd
import plotly.express as px
import plotly.io as pio
import numpy as np
import plotly.graph_objects as go
pio.renderers.default = "browser"

df = pd.read_excel('/Users/alissanicolet./Desktop/QGIS_Thesis/pythongraphexcel.xlsx')
print(df)
r_x=[0,1]
r_y=[0,1]
r_z=[0.9,2]

fig = px.scatter_3d(
    data_frame=df,
    x='GSI',
    y='OSR',
    z='FSI',
    range_x=(r_x),
    range_y=(r_y),
    range_z=(r_z),
    color="Sample",
    color_discrete_sequence=['magenta','green','blue'],
    template='seaborn',
    title='Spacematrix of Sample Areas',
    hover_name='Sample',
    height=700,
)

# 场景配置调整
fig.update_scenes(
    yaxis_autorange="reversed",
    xaxis_dtick=0.1,
    yaxis_dtick=0.1,
    # 强制正立方体渲染
    aspectmode='cube',
    # 坐标轴自动留边避免裁切
    xaxis_automargin=True,
    yaxis_automargin=True,
    zaxis_automargin=True
)

# 旋转动画初始视角
x_eye = -1.25
y_eye = 2
z_eye = 0.5

# 布局配置调整
fig.update_layout(
    scene_camera_eye=dict(x=x_eye, y=y_eye, z=z_eye),
    # 调整全局边距,避免内容裁切,顶部留60px放标题
    margin=dict(l=10, r=10, b=10, t=60),
    updatemenus=[dict(type='buttons',
                      showactive=False,
                      y=1,
                      x=0.8,
                      xanchor='left',
                      yanchor='bottom',
                      pad=dict(t=45, r=10),
                      buttons=[dict(label='Play',
                                    method='animate',
                                    args=[None, dict(frame=dict(duration=200, redraw=True),
                                                     transition=dict(duration=0),
                                                     fromcurrent=True,
                                                     mode='immediate'
                                                     )]
                                    )
                               ]
                      )
                 ]
)

def rotate_z(x, y, z, theta):
    w = x + 1j * y
    return np.real(np.exp(1j * theta) * w), np.imag(np.exp(1j * theta) * w), z

frames = []
for t in np.arange(0, 6.26, 0.1):
    xe, ye, ze = rotate_z(x_eye, y_eye, z_eye, -t)
    frames.append(go.Frame(layout=dict(scene_camera_eye=dict(x=xe, y=ye, z=ze))))
fig.frames = frames

pio.show(fig)

注:如果需要调整z轴刻度间隔,直接添加zaxis_dtick=对应间隔值配置即可,不会影响立方体显示效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:48:15