Home > OS >  Toggling Grid with Buttons in a Plotly Scatter graph in Python
Toggling Grid with Buttons in a Plotly Scatter graph in Python

Time:04-06

I am trying to make a scatter plot in Plotly containing a button that toggles the X and Y gridlines on the spot. I am using this code, but when I click the buttons, nothing happens to the gridlines.

buttons = [dict (method='update', label="Grid ON", args=[{'xaxes' : {'grid' : {'showgrid': True}}}]),
           dict (method='update', label="Grid OFF", args=[{'xaxes' : {'grid' : {'showgrid': False}}}] ),
                 ]
           

fig.update_layout(
            updatemenus=[{'buttons':buttons}]
).update_xaxes(showgrid=True, gridwidth=2, gridcolor='LightPink',
                         tickmode='linear',
                         tick0 = 0,
                         dtick = 60,
                         range = [0, 2500]
              ).update_yaxes(showgrid=True, gridwidth=2, gridcolor='LightPink',
                                      # tickmode='linear',
                                      # tick0=0,
                                      dtick=0.1,
                                      )

CodePudding user response:

  • the main issue is you are using wrong method. It should be relayout
  • there are some subtle issues where more that just visibility needs to be updated
  • I always prefer to do a list comprehension to build updatemenus structure to avoid copy-paste of similar code
import plotly.express as px
import numpy as np

fig = px.scatter(x=np.linspace(1, 2500, 20), y=np.random.uniform(0, 1, 20))

buttons = [
    {
        "method": "relayout",
        "label": l,
        "args": [
            {
                "xaxis": {
                    "showgrid": s,
                    "gridcolor": "LightPink",
                    "dtick": 60,
                    "tick0": 0,
                },
                "yaxis": {"showgrid": s, "gridcolor": "LightPink", "dtick": 0.1},
            }
        ],
    }
    for l, s in [("Grid ON", True), ("Grid OFF", False)]
]


fig.update_layout(updatemenus=[{"buttons": buttons}]).update_xaxes(
    # showgrid=True,
    # gridwidth=2,
    gridcolor="LightPink",
    # tickmode="linear",
    tick0=0,
    dtick=60,
    range=[0, 2500],
).update_yaxes(
    # showgrid=True,
    # gridwidth=2,
    gridcolor="LightPink",
    # # tickmode='linear',
    # # tick0=0,
    dtick=0.1,
)
  • Related