How to write a common Plotly graph! (add_trace,update_layout)

Plotly

In previous articles, I introduced how to use a simple visualization library called Plotly (Plotly makes graphs easier to use! ) and what kind of graphs can be written? (List of graphs you can draw with Plotly! )!

 In this article, I'm going to give you a summary of the items that are common to all graphs that I didn't get a chance to talk about there, and that you need to write about!

Main components of Plotly

 I'll focus on graph_objects, which are the four main components of plotting a graph in plotly!

➀ fig = go.Figure()
➁ fig.add_trace()
➂ fig.update_layout()
➃ fig.show()

import plotly.graph_objects as go

fig = go.Figure() # 1 
fig.add_trace( 
     #2. Add and describe a graph
)
fig.update_layout(
     #3. Decorate graphs, add restrictions (display title, maximum value for x-axis, etc.)
)
fig.show() #4.Draw graphs

I've already explained 1 and 4 in other articles, so I'll explain parts 2 and 3 with concrete examples!

Example(Changes in the price of apples)

 If we illustrate the change in the price of apples in a graph, we can make a graph like the one below!

import pandas as pd
import plotly.graph_objects as go
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_apple_stock.csv')
df = df.rename(columns={'AAPL_x':'date','AAPL_y':'price'})
fig = go.Figure() # 1 

fig.add_trace(    #2. Add and describe a graph
    go.Scatter(x = df['date'], y = df['price'],
                  name='Share Prices (in USD)')
)

fig.update_layout( #3. Decorate graphs, add restrictions (display title, maximum value for x-axis, etc.)
    title = 'Apple Share Prices over time (2014)',
    xaxis_title = 'date',
    yaxis_title = 'price',
    showlegend = True
)
fig.show() #4.Draw graphs

add_trace

 It's mainly used to add graphs!
The functions for each graph are described in The list of graphs you can draw with Plotly! For example, scatter plots would look like go.Scatter.

 In addition, common options within each graph function include the following!

Legend (name)

 After setting the name, you can display the legend by setting showlegend to Ture in update_layout.
matplotlib : The part that corresponds to the label
 

update_layout

An item that can be used to decorate the graph and add restrictions (title display, maximum value of x-axis, etc.)

title

Give the entire graph a title.

 title = 'Apple Share Prices over time (2014)'

matplotlib : plt.title("Title")

Title of each axis (xaxis_title, yaxis_title)

If you want to display the x-axis and y-axis with titles!

xaxis_title = 'date',
yaxis_title = 'price'

matplotlib : plt.xlabel("Title")
plt.ylabel("Title")

width, height 

Specify the width and height of the entire graph

showlegend

 By setting showlgend = True, the legend will be displayed.

showlegend = True

matplotlib : plt.legend()

Copied title and URL