ホーム 暮らし plotly.graph_objects and plotly.express

plotly.graph_objects and plotly.express

藤崎 健人 藤崎 健人 • 更新: • 公開: • 読了約 5 分
目次

I will explain go (plotly.graph_objects) and px (plotly.express).

Preparing sample data

n7aa5d7ff7b1d

I will use the following sample data for the explanation.

import plotly.graph_objects as go
import plotly.express as px

df = px.data.tips() # サンプルデータをとってくる

Main topic

In examples of visualization using plotly, you may have seen articles that use plotly in this way.

fig =go.Figure(data=[go.Scatter(x=df['total_bill'],y=df['tip'],mode='markers')])
fig.update_layout(xaxis=dict(title='total_bill'),yaxis=dict(title='tip'))
fig.show()

It is a bit tedious to have to write so much just to output a scatter plot, isn't it?

Seeing that, some people might think, "Plotly is convenient for creating interactive graphs, but do I have to write such tedious code?" but that is not the case.

There is a way to generate graphs that are well-formatted with minimal effort using much shorter code.

That is plotly.express.

For example, if you want to perform a visualization like this one, many people would want to use the column names as axis labels as they are. However, in graph_objects, you have to specify that explicitly, which is troublesome.

On the other hand, with plotly.express, you first specify the dataframe, and then just write the column names for x and y, and it will generate a graph with axis labels.

fig = px.scatter(df,x='total_bill',y='tip')
fig.show()

Not only are there axis labels, but the content displayed when hovering also has labels. If you are going to learn about plotly, I think you only need to learn this simple plotly.express for now.

Supplementary note

Note that plotly.express works by calling plotly.graph_objects internally. It is, so to speak, a "wrapper function" that wraps graph_objects to make it easier to handle.

It is a smooth approach to use express when you want to write code easily, and only touch graph_objects directly when you need detailed customization that express cannot reach.


同じカテゴリの記事

藤崎 健人

芸能取材歴10年のデスク。所属事務所の公式リリース、番組公式サイト、配信サービスの告知を一次情報として採用し、裏付けの取れない内容は記事にしていません。

おすすめの関連記事