go :: Graph Objects

Published by onesixx on

https://plotly.com/graphing-libraries/

traces = []
for 
    traces.append (go.Scatter())

layout = go.Layout()

fig = go.Figure(data=trace, layout)
fig.show()
traces=[]
for year  in years:
    # year='2020'
    temp_df = df_g[df_g['year']==year]
    traces.append(
        go.Scatter( x=temp_df['month'], y=temp_df['Revenue'], 
            mode = 'lines+markers',
            marker = dict(size=10),
            name = year
        )
    )
layout = go.Layout(title="ch2.2", yaxis=dict(title='Revenue'))
fig = go.Figure(traces, layout)
fig.show()

Python Fundamentals > Graph Objects

Plotly Python Open Source Graphing Library : Basic Charts
Plotly Python Open Source Graphing Library : Fundamentals

plotly.graph_objects: figures, traces and layout에 대한 low-level interface

import plotly.graph_objects as go

fig = go.Figure(
    data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])],
    layout=go.Layout(
        title=go.layout.Title(text="A Figure Specified By A Graph Object")
    )
)

fig.show()
import plotly.graph_objects as go

trace = go.Bar(x=[1, 2, 3], y=[1, 3, 2])
pdata = [trace]
layout = go.Layout(
  title=go.layout.Title(text="A Figure Specified By A Graph Object"
)

fig = go.Figure(
    pdata, layout
)

fig.show()

Graph Objects 란?

plotly 파이썬 라이브러리가 생성/조작/랜더링한 Figures는 Plotly.js JavaScript 라이브러리가 랜더링을 위해 자동으로 JSON으로 serialized한 tree와 같은 데이터구조를 나타낸다. => Plotly의 python라이브러리나 JavaScript라이브러리나 비슷하다.

이런 tree는 “attributes”라는 명명된 node로 구성되고, 그 구조는 plotly.js 에 의해 정의된다.

import plotly.graph_object as go 는 파이썬 클래스의 자동생성된 계층구조를 가진다..

These trees are composed of named nodes called “attributes”, with their structure defined by the Plotly.js figure schema, which is available in machine-readable form

The plotly.graph_objects module (typically imported as go) contains an automatically-generated hierarchy of Python classes which represent non-leaf nodes in this figure schema. The term “graph objects” refers to instances of these classes.

The primary classes defined in the plotly.graph_objects module are Figure 

and an ipywidgets-compatible variant called FigureWidget, which both represent entire figures.

Instances of these classes have many convenience methods for Pythonically manipulating their attributes (e.g. .update_layout() or .add_trace(), which all accept “magic underscore” notation) as well as rendering them (e.g. .show()) and exporting them to various formats (e.g. .to_json() or .write_image() or .write_html()).

Note: the functions in Plotly Express, which is the recommended entry-point into the plotly library, are all built on top of graph objects, and all return instances of plotly.graph_objects.Figure.

Every non-leaf attribute of a figure is represented by an instance of a class in the plotly.graph_objects hierarchy. For example, a figure fig can have an attribute layout.margin, which contains attributes tlb and r which are leaves of the tree: they have no children. The field at fig.layout is an object of class plotly.graph_objects.Layout and fig.layout.margin is an object of class plotly.graph_objects.layout.Margin which represents the margin node, and it has fields tlb and r, containing the values of the respective leaf-nodes. Note that specifying all of these values can be done without creating intermediate objects using “magic underscore” notationgo.Figure(layout_margin=dict(t=10, b=10, r=10, l=10)).

The objects contained in the list which is the value of the attribute data are called “traces”, and can be of one of more than 40 possible types, each of which has a corresponding class in plotly.graph_objects. For example, traces of type scatter are represented by instances of the class plotly.graph_objects.Scatter. This means that a figure constructed as go.Figure(data=[go.Scatter(x=[1,2], y=[3,4)]) will have the JSON representation {"data": [{"type": "scatter", "x": [1,2], "y": [3,4]}]}.

Graph Objects Compared to Dictionaries

Graph objects는 딕셔너리와 비교해서 여러가지 장점이 있다.

  1. Graph objects provide precise data validation.
    If you provide an invalid property name or an invalid property value as the key to a graph object, an exception will be raised with a helpful error message describing the problem. This is not the case if you use plain Python dictionaries and lists to build your figures.
  2. Graph objects contain descriptions of each valid property as Python docstrings, with a full API reference available.
    You can use these docstrings in the development environment of your choice to learn about the available properties as an alternative to consulting the online Full Reference.
  3. Properties of graph objects can be accessed using both dictionary-style key lookup (e.g. fig["layout"]) or class-style property access (e.g. fig.layout).
  4. Graph objects support higher-level convenience functions for making updates to already constructed figures (.update_layout().add_trace() etc).
  5. Graph object constructors and update methods accept “magic underscores” (e.g. go.Figure(layout_title_text="The Title") rather than dict(layout=dict(title=dict(text="The Title")))) for more compact code.
  6. Graph objects support attached rendering (.show()) and exporting functions (.write_image()) that automatically invoke the appropriate functions from the plotly.io module.

When to use Graph Objects vs Plotly Express

figure생성은 가능하다면 plotly.express모듈의 function을 사용하는 것이 좋다.

모든 px(Plotly Express) function는  내부적으로 graph objects 사용하고,
 plotly.graph_objects.Figure instance를 return한다.

The recommended way to create figures is using the functions in the plotly.express module
collectively known as Plotly Express, which all return instances of plotly.graph_objects.Figure, so every figure produced with the plotly library actually uses graph objects under the hood, unless manually constructed out of dictionaries.

That said, certain kinds of figures are not yet possible to create with Plotly Express, such as figures that use certain 3D trace-types like mesh or isosurface. In addition, certain figures are cumbersome to create by starting from a figure created with Plotly Express, for example figures with subplots of different typesdual-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 (or one configured with subplots via the make_subplots() function) and progressively add traces and update attributes as above. Every plotly documentation page lists the Plotly Express option at the top if a Plotly Express function exists to make the kind of chart in question, and then the graph objects version below.

Note that the figures produced by Plotly Express in a single function-call are easy to customize at creation-time, and to manipulate after creation using the update_* and add_* methods.

Comparing Graph Objects and Plotly Express

px(고수준)를 통해 만들어진 figure는 항상 go(저수준)로 만들수 있지만, 꽤 많은 코딩 필요하다.

px는 단순히 짧은 코딩뿐아니라 여러 데이터 형태를 다룰수 있다
Plotly Express also accepts data in “wide form”


More complex figures such as sunburstsparallel coordinatesfacet plots or animations require many more lines of figure-specific graph objects code,
whereas switching from one representation to another with Plotly Express usually involves changing just a few characters.

px vs. go

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,
\t\t\thovertemplate="Contestant=%s
Fruit=%%{x}
Number Eaten=%%{y}"% contestant) \t) fig.update_layout(legend_title_text = "Contestant") fig.update_xaxes(title_text="Fruit") fig.update_yaxes(title_text="Number Eaten") fig.show()

Dash 활용

fig.show() 대신 dash에 Graph component (from dcc)

import plotly.graph_objects as go 
fig = go.Figure()                 
# fig.add_trace( ... )
# fig.update_layout( ... )

## or
import plotly.express as px
fig = px.bar(...)

#- -------------------------------------
import dash
from dash import Dash, dcc, html

app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter
Categories: visualization

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x