【问题标题】:Plotly set showgrid = False for ALL subplots为所有子图设置 showgrid = False
【发布时间】:2021-07-31 05:40:25
【问题描述】:

我有 10 多个子图,我想禁用 showgrid=False 的网格线。我需要对 x 轴和 y 轴都这样做。

This answer 似乎很接近,但我无法扩展它来做我想做的事。

在上面的答案中,他们展示了如何设置所有子图的范围:

myRange=[0,6]
for ax in fig['layout']:
    if ax[:5]=='xaxis':
        fig['layout'][ax]['range']=myRange

但是当我尝试使用showgrid 时,我收到错误TypeError: 'NoneType' object does not support item assignment

我试过了:

for ax in fig['layout']:
    fig['layout'][ax]['showgrid'] = False

仅使用 update_layout 只会更改第一个子图:

fig.update_layout(
     xaxis=dict(showgrid=False), 
     yaxis=dict(showgrid=False)
)

【问题讨论】:

    标签: python plotly


    【解决方案1】:

    您自己的建议可行,但对于任意数量的子图,以下建议更灵活:

    fig.for_each_xaxis(lambda x: x.update(showgrid=False))
    fig.for_each_yaxis(lambda x: x.update(showgrid=False))
    

    完整代码:

    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    fig = make_subplots(rows=2, cols=2, start_cell="bottom-left")
    
    fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
                  row=1, col=1)
    
    fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
                  row=1, col=2)
    
    fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]),
                  row=2, col=1)
    
    fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]),
                  row=2, col=2)
    
    fig.for_each_xaxis(lambda x: x.update(showgrid=False))
    fig.for_each_yaxis(lambda x: x.update(showgrid=False))
    
    fig.show()
    

    【讨论】:

      【解决方案2】:

      我找到了answer in the Plotly forums。使用fig['layout']['xaxis7'].update(showgrid=False)(1 个索引)。示例:

      for i in range(10):
          fig['layout'][f'xaxis{i+1}'].update(showgrid=False)
          fig['layout'][f'yaxis{i+1}'].update(showgrid=False)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-03
        • 2019-05-29
        • 2020-11-22
        • 2016-06-24
        • 1970-01-01
        • 2014-12-27
        • 2023-03-13
        相关资源
        最近更新 更多