본문 바로가기

Data Science/Visualization

[plotly] Graph Objects in Python

1. What is Figure objects?

The plotly Python package exists to create, manipulate and render graphical figures represented by data structures also referred to as figures. Figures can be represented in Python either as dicts or as instances of the plotly.graph_objects.Figure class, and are serialized as text in JSON before being passed to Plotly.js.

 

Figure({
    'data': [{'hovertemplate': 'x=%{x}<br>y=%{y}<extra></extra>',
              'legendgroup': '',
              'line': {'color': '#636efa', 'dash': 'solid'},
              'marker': {'symbol': 'circle'},
              'mode': 'lines',
              'name': '',
              'orientation': 'v',
              'showlegend': False,
              'type': 'scatter',
              'x': array(['a', 'b', 'c'], dtype=object),
              'xaxis': 'x',
              'y': array([1, 3, 2]),
              'yaxis': 'y'}],
    'layout': {'legend': {'tracegroupgap': 0},
               'template': '...',
               'title': {'text': 'sample figure'},
               'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'x'}},
               'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'y'}}}
})

 

2. Graph Objects Compared to Dictionaries

  • Graph objects provide precise data validation.
  • Graph objects contain descriptions of each valid property as Python docstrings, with a full API reference available.
  • Properties of graph objects can be accessed using both dictionary-style ke loopup or class-style property access(e.g. fig.layout).
  • Graph objects support higher-level convenience functions for making updates to already constructed figures(e.g. fig.update_layout, fig.add_trace, etc).
  • Graph object constructors and update method accept magic underscores(e.g. go.Figure(layout_title_text="Title" rather than dict(layout=dict(title=dict(text="Title")))). 
  • Graph objects support attached rendering(e.g. fig.show()).

 

3. When to use Graph Objects vs Plotly Express

The recommended way to create figures is using the functions in the plotly.express module, which all return instances of plotly.graph_objects.Figure.

 

Certain kinds of figures are not yet possible to create with Plotly Express, such as figures that use certain 3D trace-types, subplots of different types, dual-axis plots, or faceted plots with multiple different types of traces. To construct such figures, it can be easier to start from an empty plotly.graph_objects.Figure object and progressively add traces and update attirubtes.

 

4. Differences of code between Graph Objects vs Plotly Express

import pandas as pd

df = pd.DataFrame({
  "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
  "Contestant": ["Alex", "Alex", "Alex", "Jordan", "Jordan", "Jordan"],
  "Number Eaten": [2, 1, 3, 1, 3, 2],
})


# Plotly Express

import plotly.express as px

fig = px.bar(df, x="Fruit", y="Number Eaten", color="Contestant", barmode="group")
fig.show()


# Graph Objects

import plotly.graph_objects as go

fig = go.Figure()
for contestant, group in df.groupby("Contestant"):
    fig.add_trace(go.Bar(x=group["Fruit"], y=group["Number Eaten"], name=contestant,
      hovertemplate="Contestant=%s<br>Fruit=%%{x}<br>Number Eaten=%%{y}<extra></extra>"% contestant))
fig.update_layout(legend_title_text = "Contestant")
fig.update_xaxes(title_text="Fruit")
fig.update_yaxes(title_text="Number Eaten")
fig.show()

 

5. How to code Graph Objects

Step 1 : Import libraries

# Import libraries 
import plotly.graph_objects as go 
import numpy as np
np.random.seed(42)

 

Step 2 : Declare an empty figure object

fig = go.Figure()

 

Step 3 : Add trace or layout to empty figure

for company in ["A", "B"]: 
    fig.add_trace(go.Scatter(
	    x = df.loc[df.company == company, "time"],
        y = df.loc[df.company == company, "price"],
        name = company 
    ))

 

Step 4 : Show figure using method

fig.show()

 

6. Two ways creating figures object

# Import libraries 
import plotly.graph_objects as go 
import numpy as np
np.random.seed(42) 

# Simulate data 
returns_A = np.random.normal(0.01, 0.2, 100)
returns_B = np.random.normal(0.01, 0.2, 100)
returns = np.append(returns_A, returns_B)

prices_A = 100 * np.exp(returns_A.cumsum())
prices_B = 100 * np.exp(returns_B.cumsum())
prices = np.append(prices_A, prices_B)

companies = ["A"] * 100 + ["B"] * 100
time = np.append(np.arange(100), np.arange(100))

df = pd.DataFrame({
    "company": companies,
    "time": time,
    "price": prices,
    "returns": returns
})

# Visaulization way 1 : Add additional components to empty figure
fig = go.Figure() 
for company in ["A", "B"]: 
    fig.add_trace(go.Scatter(
	    x = df.loc[df.company == company, "time"],
        y = df.loc[df.company == company, "price"],
        name = company 
    ))
fig.show()


# Visualization way 2 : Define figure with previously written components 
# Build graph 
layout = go.Layout(
    title="Performance of A vs. B", 
    plot_bgcolor="#FFFFFF", 
    hovermode="x", 
    hoverdistance=100, # Distance to show hover label of data point
    spikedistance=1000, # Distance to show spike
    xaxis=dict(
        title="time",
        linecolor="#BCCCDC",
        showspikes=True, # Show spike line for X-axis
        # Format spike
        spikethickness=2,
        spikedash="dot",
        spikecolor="#999999",
        spikemode="across",
    ),
    yaxis=dict(
        title="price",
        linecolor="#BCCCDC"
    )   
) 

data = []
for company in ["A", "B"]:
    time = df.loc[df.company == company, "time"]
    price = df.loc[df.company == company, "price"]
    returns = df.loc[df.company == company, "returns"]
    line_chart = go.Scatter(
        x=time,
        y=price,
        name=company
    )
    data.append(line_chart)
    
fig = go.Figure(data=data, layout=layout) 
fig.show()

 

 

 

Source from : https://plotly.com/python/graph-objects/

'Data Science > Visualization' 카테고리의 다른 글

[plotly] Layout components of plotly  (0) 2022.09.18
[plotly] Plotly Express in Python  (0) 2022.09.18
[plotly] iplot in Python  (0) 2022.09.18
[plotly] Getting Started with Plotly in Python  (0) 2022.09.18