How to make all subplots have same xticks and yticks in plotly?

Viewed 209

I have been trying to change the xticks and yticks in plotly for many hours but still could not make all the subplots have the same range of xticks and yticks.

Required

  • All the subplots xticks must be Jan Feb Mar Apr May Jun.
  • All the subplots yticks must be 0.0% to 0.8% including both.

My Code So Far

import numpy as np
import pandas as pd


from plotly.subplots import make_subplots
import plotly.graph_objects as go

df = pd.DataFrame({'Month': ['2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'],
          'Site A': [0.0006171, 0.0007480000000000001, 0.00041139999999999997, 0.0005422999999999999, 9.35e-05, 0.0011407],
          'Site B': [0.0003927000000000001, 0.0026, 0.0008041000000000001, 0.0005797, 0.0008789000000000001, 0.0004301000000000001],
          'Site C': [0.0075548, 0.0045815000000000005, 0.0033473, 0.0016455999999999999, 0.0023375, 0.00229],
          'Site D': [0.0007854000000000001, 0.0003927000000000001, 0.0013277, 0.0005235999999999999, 0.0008227999999999999, 0.0016082000000000002],
          'Site E': [0.0, 0.0007480000000000001, 0.0, 0.0015520999999999998, 0.0005984000000000001, 0.00014],
          'Site F': [0.0, 0.0007292999999999999, 0.0, 0.0002431, 0.0, 0.0],
          'Site G': [0.0006919000000000001, 0.0008976000000000001, 0.0005422999999999999, 0.0007667, 0.0008414999999999999, 0.0008],
          'Site H': [0.00257, 0.00324, 0.00512, 0.00197, 0.0009199999999999999, 0.0004301000000000001],
          'Site I': [0.0013277, 0.0, 0.0, 0.0, 0.0, 0.0013277]})


df['Month'] = pd.to_datetime(df['Month'])
df = df.set_index('Month')


cols = ("Site H", "Site E", "Site B",
        "Site C", "Site G", "Site F",
        "Site D", "Site I", "Site A",
        )

colors = [['darkgreen','limegreen','lightgreen'],
          ['black','gray','silver'],
          ['darkred','tomato','lightsalmon'],
          ]

fig = make_subplots(rows=3,cols=3,
                    start_cell='top-left',
                    column_widths = [1200]*3,
                    x_title = 'Month',
                    subplot_titles=cols
                   )

fig.add_scatter(x=df.index, y=df['Site H'],  row=1, col=1, showlegend=False, line=dict(color=colors[0][0]),  mode='lines+markers', name='Site H')
fig.add_scatter(x=df.index, y=df['Site E'],  row=1, col=2, showlegend=False, line=dict(color=colors[0][1]))
fig.add_scatter(x=df.index, y=df['Site B'],  row=1, col=3, showlegend=False, line=dict(color=colors[0][2]))

fig.add_scatter(x=df.index, y=df['Site C'],  row=2, col=1, showlegend=False, line=dict(color=colors[1][0]))
fig.add_scatter(x=df.index, y=df['Site G'],  row=2, col=2, showlegend=False, line=dict(color=colors[1][1]))
fig.add_scatter(x=df.index, y=df['Site F'],  row=2, col=3, showlegend=False, line=dict(color=colors[1][2]))

fig.add_scatter(x=df.index, y=df['Site D'],  row=3, col=1, showlegend=False, line=dict(color=colors[2][0]))
fig.add_scatter(x=df.index, y=df['Site I'],  row=3, col=2, showlegend=False, line=dict(color=colors[2][1]))
fig.add_scatter(x=df.index, y=df['Site A'],  row=3, col=3, showlegend=False, line=dict(color=colors[2][2]))

fig.update_xaxes(tickangle=90, tickformat="%b")
fig.update_yaxes(tickformat=".1%")

tickvals = [i/1000 for i in range(1,9)]

# fig.update_yaxes(row=1, col=1, title='Success',    title_font_color="darkgreen", autorange = True, dtick=0.001)
fig.update_yaxes(row=1, col=1, title='Success',    title_font_color=colors[0][0], autorange = True, tickmode='array', tickvals=tickvals)
fig.update_yaxes(row=2, col=1, title='Status Quo', title_font_color=colors[1][0], autorange = True, dtick=0.001)
fig.update_yaxes(row=3, col=1, title='Watch',      title_font_color=colors[2][0], autorange = True, dtick=0.001)

fig.update_layout(
    title='2020 Monthy Error Rate by Site',
    title_x=0.5,
    autosize=False,
    width=800,
    height=800,
    margin=dict(
        l=120,
        r=30,
        b=80,
        t=80,
        pad=0
    ),
    paper_bgcolor="LightSteelBlue",
)

fig.add_annotation(dict(font=dict(color="black",size=14),
                            x=-0.16,
                            y=0.5,
                            showarrow=False,
                            text='Error Rate (%)',
                            textangle=-90,
                            xref="paper",
                            yref="paper"
                           )
                  )

fig.show()

My output

enter image description here

1 Answers

We can tackle each part separately. The .strftime('%b') method will extract the month abbreviation from datetimes. And we can use the .update method to set the range on fig['layout']['yaxis1'],...,fig['layout']['yaxis9'] which will allow you access each of the subplots, and we will want to set the parameter autorange to False. Putting this in a loop is best.

import numpy as np
import pandas as pd

from plotly.subplots import make_subplots
import plotly.graph_objects as go

df = pd.DataFrame({'Month': ['2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01', '2020-05-01', '2020-06-01'],
          'Site A': [0.0006171, 0.0007480000000000001, 0.00041139999999999997, 0.0005422999999999999, 9.35e-05, 0.0011407],
          'Site B': [0.0003927000000000001, 0.0026, 0.0008041000000000001, 0.0005797, 0.0008789000000000001, 0.0004301000000000001],
          'Site C': [0.0075548, 0.0045815000000000005, 0.0033473, 0.0016455999999999999, 0.0023375, 0.00229],
          'Site D': [0.0007854000000000001, 0.0003927000000000001, 0.0013277, 0.0005235999999999999, 0.0008227999999999999, 0.0016082000000000002],
          'Site E': [0.0, 0.0007480000000000001, 0.0, 0.0015520999999999998, 0.0005984000000000001, 0.00014],
          'Site F': [0.0, 0.0007292999999999999, 0.0, 0.0002431, 0.0, 0.0],
          'Site G': [0.0006919000000000001, 0.0008976000000000001, 0.0005422999999999999, 0.0007667, 0.0008414999999999999, 0.0008],
          'Site H': [0.00257, 0.00324, 0.00512, 0.00197, 0.0009199999999999999, 0.0004301000000000001],
          'Site I': [0.0013277, 0.0, 0.0, 0.0, 0.0, 0.0013277]})

df['Month'] = pd.to_datetime(df['Month'])
df['Month'] = [mydate.strftime('%b') for mydate in df['Month']]
df = df.set_index('Month')

cols = ("Site H", "Site E", "Site B",
        "Site C", "Site G", "Site F",
        "Site D", "Site I", "Site A",
        )

colors = [['darkgreen','limegreen','lightgreen'],
          ['black','gray','silver'],
          ['darkred','tomato','lightsalmon'],
          ]

fig = make_subplots(rows=3,cols=3,
                    start_cell='top-left',
                    column_widths = [1200]*3,
                    x_title = 'Month',
                    subplot_titles=cols
                   )

fig.add_scatter(x=df.index, y=df['Site H'],  row=1, col=1, showlegend=False, line=dict(color=colors[0][0]),  mode='lines+markers', name='Site H')
fig.add_scatter(x=df.index, y=df['Site E'],  row=1, col=2, showlegend=False, line=dict(color=colors[0][1]))
fig.add_scatter(x=df.index, y=df['Site B'],  row=1, col=3, showlegend=False, line=dict(color=colors[0][2]))

fig.add_scatter(x=df.index, y=df['Site C'],  row=2, col=1, showlegend=False, line=dict(color=colors[1][0]))
fig.add_scatter(x=df.index, y=df['Site G'],  row=2, col=2, showlegend=False, line=dict(color=colors[1][1]))
fig.add_scatter(x=df.index, y=df['Site F'],  row=2, col=3, showlegend=False, line=dict(color=colors[1][2]))

fig.add_scatter(x=df.index, y=df['Site D'],  row=3, col=1, showlegend=False, line=dict(color=colors[2][0]))
fig.add_scatter(x=df.index, y=df['Site I'],  row=3, col=2, showlegend=False, line=dict(color=colors[2][1]))
fig.add_scatter(x=df.index, y=df['Site A'],  row=3, col=3, showlegend=False, line=dict(color=colors[2][2]))

fig.update_xaxes(tickangle=90, tickformat="%b", type='category')
fig.update_yaxes(tickformat=".1%")

tickvals = [i/1000 for i in range(1,9)]

# fig.update_yaxes(row=1, col=1, title='Success',    title_font_color="darkgreen", autorange = True, dtick=0.001)
fig.update_yaxes(row=1, col=1, title='Success',    title_font_color=colors[0][0], autorange = True, tickmode='array', tickvals=tickvals)
fig.update_yaxes(row=2, col=1, title='Status Quo', title_font_color=colors[1][0], autorange = True, tickmode='array', tickvals=tickvals)
fig.update_yaxes(row=3, col=1, title='Watch',      title_font_color=colors[2][0], autorange = True, tickmode='array', tickvals=tickvals)

# updates fig['layout']['yaxis1']... fig['layout']['yaxis9']
for i in range(1,10):
    fig['layout']['yaxis' + str(i)].update(range=[0, 0.008], autorange=False)

fig.update_layout(
    title='2020 Monthy Error Rate by Site',
    title_x=0.5,
    autosize=False,
    width=800,
    height=800,
    margin=dict(
        l=120,
        r=30,
        b=80,
        t=80,
        pad=0
    ),
    paper_bgcolor="LightSteelBlue",
)

fig.add_annotation(dict(font=dict(color="black",size=14),
                            x=-0.16,
                            y=0.5,
                            showarrow=False,
                            text='Error Rate (%)',
                            textangle=-90,
                            xref="paper",
                            yref="paper"
                           )
                  )

fig.show()

enter image description here

Related