3

I've got 10+ subplots which I want to disable the grid lines for showgrid=False. I need to do that for both x and y axes.

This answer seems to be close, but I can't extend it to do what I want.

In the answer above they show how to set the range for all subplots:

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

But when I try that with showgrid I get an error TypeError: 'NoneType' object does not support item assignment

I tried:

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

Using just update_layout only changes the first subplot:

fig.update_layout(
     xaxis=dict(showgrid=False), 
     yaxis=dict(showgrid=False)
)
vestland
  • 55,229
  • 37
  • 187
  • 305
David Parks
  • 30,789
  • 47
  • 185
  • 328

2 Answers2

4

Your own suggestion works, but the following is more flexible for an arbitrary number of subplots:

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

enter image description here

Complete code:

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()
vestland
  • 55,229
  • 37
  • 187
  • 305
2

I found the answer in the Plotly forums. Use fig['layout']['xaxis7'].update(showgrid=False) (1 indexed). Example:

for i in range(10):
    fig['layout'][f'xaxis{i+1}'].update(showgrid=False)
    fig['layout'][f'yaxis{i+1}'].update(showgrid=False)
David Parks
  • 30,789
  • 47
  • 185
  • 328