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

如何在Plotly自定义主题中设置固定绘图宽高适配pandas.plot调用

原因说明

你自定义模板中的边距配置生效,是因为边距属于Plotly主题样式的覆盖范畴,而宽高参数默认属于单图表的实例配置项,优先级高于模板设定,因此模板里的width、height不会被自动应用。

可行方案

方案1:配置pandas plotly后端全局参数(推荐)

不需要修改现有绘图调用逻辑,只需新增几行全局配置即可:

import pandas as pd
import plotly.io as pio

# 配置自定义模板,设置边距等全局样式
pio.templates["custom"] = pio.templates["plotly"]
pio.templates["custom"].layout.margin = dict(l=0, r=0, t=0, b=0)
pio.templates.default = "custom"

# 设置pandas plotly绘图后端
pd.options.plotting.backend = "plotly"
# 直接配置全局默认宽高
pd.options.plotting.plotly.width = 200
pd.options.plotting.plotly.height = 200

# 测试绘图
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
df = pd.DataFrame({"x": x, "y": y})

fig = df.plot(x="x", y="y")
fig.show()

方案2:封装自定义绘图方法

如果后续需要添加更多全局统一配置,可封装通用绘图函数,灵活性更高:

import pandas as pd
import plotly.io as pio

pd.options.plotting.backend = "plotly"
pio.templates.default = "plotly"

def df_plot(df, *args, **kwargs):
    fig = df.plot(*args, **kwargs)
    # 所有全局统一配置都可在此处添加
    fig.update_layout(
        width=200, 
        height=200, 
        margin=dict(l=0, r=0, t=0, b=0)
    )
    return fig

# 调用示例
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
df = pd.DataFrame({"x": x, "y": y})
fig = df_plot(df, x="x", y="y")
fig.show()

内容的提问来源于stack exchange,提问作者Saaru Lindestøkke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:24:05