[PYTHON] Create graph with plotly button

Thing you want to do

--Create a button in the graph and press the button to show / hide the plot --Change the graph title, y-axis label, etc. when the button is pressed

environment

pip

python


pip install plotly
pip install numpy

Sample graph

Switch between 1st to 3rd order with 3 buttons, change title and y-axis label

See the Pen plotly_button by shunta-m (@shunta-m) on CodePen.

python


import numpy as np
import plotly.offline as offline
import plotly.graph_objs as go

x = np.linspace(-5, 5, 11)
y1 = x
y2 = x ** 2
y3 = x ** 3

trace1 = go.Scatter(
    x=x,
    y=y1,
    name="y1",
    mode="lines",
    line=dict(color="red"),
    visible=False,
    showlegend=True
)

trace2 = go.Scatter(
    x=x,
    y=y2,
    name="y2",
    mode="lines",
    line=dict(color="green"),
    visible=False,
    showlegend=True
)

trace3 = go.Scatter(
    x=x,
    y=y3,
    name="y3",
    mode="lines",
    line=dict(color="blue"),
    visible=False,
    showlegend=True
)

data = [trace1, trace2, trace3]
#0th of data as initial state(trace1)To be visible
data[0].visible = True

"""
Key description

active:Specify the button that is pressed in the initial state, and enter the list index of the buttons key value
x:x coordinate, in the graph(Light blue part)The left end of is 0,The right end is 1, default=-0.05
xanchor:Where to the x coordinate button(Right edge, left edge, etc.)To match, ("auto" | "left" | "center" | "right"), default="right"
y:x coordinate, in the graph(Light blue part)The bottom edge of is 0,Top 1, default=1
yanchor:Where to button the y coordinate(Bottom edge, top edge, etc.)To match, ( "auto" | "top" | "middle" | "bottom" ), default="top"
direction:Orientation of buttons, ( "left" | "right" | "up" | "down" ), default="down"
type:Dropdown or button( "dropdown" | "buttons" ), default="dropdown"
buttons:Button settings
"""
updatemenus = [dict(active=0, x=-0.05, xanchor="right", y=1, yanchor="top", direction="up", type="buttons", buttons=[
    dict(label=trace1.name,
         method="update",
         args=[dict(visible=[True, False, False]),
               dict(title="button_plotly_{}".format(trace1.name),
                    yaxis=dict(title="yaxis_{}".format(trace1.name), showspikes=True))]),

    dict(label=trace2.name,
         method="update",
         args=[dict(visible=[False, True, False]),
               dict(title="button_plotly_{}".format(trace2.name),
                    yaxis=dict(title="yaxis_{}".format(trace2.name), showspikes=True), )]),

    dict(label=trace3.name,
         method="update",
         args=[dict(visible=[False, False, True]),
               dict(title="button_plotly_{}".format(trace3.name),
                    yaxis=dict(title="yaxis_{}".format(trace3.name), showspikes=True))]),
])]

layout = go.Layout(
    title="button_plotly_y1",
    xaxis=dict(title="xaxis", showspikes=True, domain=[0.05, 1.0]),
    yaxis=dict(title="yaxis_y1", showspikes=True),
    font=dict(size=16),
    legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
    newshape=dict(line_color='#00ffff'),
    hoverlabel=dict(font_size=20),
    autosize=True,
    updatemenus=updatemenus,
    showlegend=True,
)

fig = dict(data=data, layout=layout)

offline.plot(fig, auto_open=True, include_plotlyjs="cdn", filename=r"./button_plotly.html",
             config={'modeBarButtonsToAdd': ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect',
                                             'eraseshape']})

Details

python


"""
Key description

active:Specify the button that is pressed in the initial state, and enter the list index of the buttons key value
x:x coordinate, in the graph(Light blue part)The left end of is 0,The right end is 1, default=-0.05
xanchor:Where to the x coordinate button(Right edge, left edge, etc.)To match, ("auto" | "left" | "center" | "right"), default="right"
y:x coordinate, in the graph(Light blue part)The bottom edge of is 0,Top 1, default=1
yanchor:Where to button the y coordinate(Bottom edge, top edge, etc.)To match, ( "auto" | "top" | "middle" | "bottom" ), default="top"
direction:Orientation of buttons, ( "left" | "right" | "up" | "down" ), default="down"
type:Dropdown or button( "dropdown" | "buttons" ), default="dropdown"
buttons:Button settings
"""
updatemenus = [dict(active=0, x=-0.05, xanchor="right", y=1, yanchor="top", direction="up", type="buttons", buttons=[
    dict(label=trace1.name,
         method="update",
         args=[dict(visible=[True, False, False]),
               dict(title="button_plotly_{}".format(trace1.name),
                    yaxis=dict(title="yaxis_{}".format(trace1.name), showspikes=True))]),

updatemenus is a list of dictionaries Create buttons for the "buttons" key value in the dictionary

label = trace1.name: Button label setting method =" update ": To change (update) the display / non-display of the graph

method Parent: layout.updatemenus[].buttons[] Type: enumerated , one of ( "restyle" | "relayout" | "animate" | "update" | "skip" ) Default: "restyle"

args=[dict(visible=[True, False, False]),dict(...)]: Graph update content, the first dict is the plot display / non-display setting A trace is displayed where the visible value is True. ex) data = [trace1, trace2, trace3], so trace1 is displayed in the above case, otherwise it is hidden.

Update other layouts with the second dict, this time update the graph title and y-axis label

python


layout = go.Layout(
    title="button_plotly_y1",
    xaxis=dict(title="xaxis", showspikes=True, domain=[0.05, 1.0]),
    yaxis=dict(title="yaxis_y1", showspikes=True),
    font=dict(size=16),
    legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
    newshape=dict(line_color='#00ffff'),
    hoverlabel=dict(font_size=20),
    autosize=True,
    updatemenus=updatemenus,
    showlegend=True,
)

Add the button created by updatemenus = updatemenus to the layout

python


fig = dict(data=data, layout=layout)

offline.plot(fig, auto_open=True, include_plotlyjs="cdn", filename=r"./button_plotly.html",
             config={'modeBarButtonsToAdd': ['drawline', 'drawopenpath', 'drawclosedpath', 'drawcircle', 'drawrect',
                                             'eraseshape']})

fig creation and output config = {...} adds a drawing button on the upper right

Reference site

official Custom Buttons | Python | Plotly layout.updatemenus | Python | Plotly

layout.xaxis.domain What is the domain attribute written in Plotly's Layout? --Qiita

Recommended Posts

Create graph with plotly button
Make a nice graph with plotly
Create a graph with borders removed with matplotlib
A memo that made a graph animated with plotly
Candlestick with plotly + Jupyter
Band graph with matplotlib
Create games with Pygame
Create filter with scipy
3D display with plotly
Creating a graph using the plotly button and slider
Candle chart plot with plotly
Graph Excel data with matplotlib (1)
Create an environment with virtualenv
Draw a graph with NetworkX
Create Cloud TPU with tf-nightly
Create an API with Django
Create / search / create table with PynamoDB
Create 3d gif with python3
Create a homepage with django
Graph drawing method with matplotlib
Graph Excel data with matplotlib (2)
Create Image Viewer with Tkinter
Create SVG graph with matplotlib on heroku (displayed in Japanese)
Create custom rules with ElastAlert
Create patent map with Streamlit
Create a heatmap with pyqtgraph
[Visualization] I want to draw a beautiful graph with Plotly
Create a directory with python
Draw a graph with networkx
Graph drawing with IPython Notebook
Create xlsx file with XlsxWriter
Create plot animation with Python + Matplotlib
Create Awaitable with Python / C API
Draw a graph with Julia + PyQtGraph (2)
Publish nice graphs online with plotly
[AWS] Create API with API Gateway + Lambda
Learn with PyTorch Graph Convolutional Networks
Draw a loose graph with matplotlib
Create a virtual environment with Python!
Create an Excel file with Python3
Draw a graph with Julia + PyQtGraph (1)
Draw a graph with Julia + PyQtGraph (3)
Output the call graph with PyCallGraph
Create LGTM images with GIMP! (Python-fu)
Dynamically create new dataframes with pandas
Create noise-filled audio data with SoX
Create basic algorithms with Smart Trade
Draw a graph with pandas + XlsxWriter
Create API using hug with mod_wsgi
Create an age group with pandas
Let's make a graph with python! !!
Create a poisson stepper with numpy.random
Create github pages with lektor Part 1
Draw a graph with PySimple GUI
Output networkX graph with graphviz (PyGraphviz)
Graph Based Segmentation with Python + OpenCV
Create a file uploader with Django
Application of graphs with plotly sliders
Create a web app that can be easily visualized with Plotly Dash
Create a Python3 environment with pyenv on Mac and display a NetworkX graph