Plotlyの基本#
Show code cell content
import plotly
plotly.__version__
'5.19.0'
Plotlyの主要なオブジェクト#
Show code cell content
# Pandasをpdとしてインポート
import pandas as pd
# Plotlyの低レベルインターフェースであるgraph_objectsをgoとしてインポート
import plotly.graph_objects as go
Show code cell source
# tag:hide
RENDERER = "plotly_mimetype+notebook"
def show_fig(fig):
"""
所定のレンダラーを用いてplotlyの図を表示
Jupyter Bookなどの環境での正確な表示を目的とする
Parameters
----------
fig : Figure
表示対象のplotly図
Returns
-------
None
"""
# 図の周囲の余白を設定
# t: 上余白
# l: 左余白
# r: 右余白
# b: 下余白
fig.update_layout(margin=dict(t=25, l=25, r=25, b=25))
# 所定のレンダラーで図を表示
fig.show(renderer=RENDERER)
figure:グラフの描画領域#
Show code cell content
# figとしてFigureクラスのインスタンスを初期化
fig = go.Figure()
Show code cell source
# 空のfigureを表示
show_fig(fig)
trace:グラフの実体#
Show code cell content
# マンガ各話データを格納したcm_ce.csvをdf_ceとして読み込み
df_ce = pd.read_csv("../../../data/cm/input/cm_ce.csv")
Show code cell content
# df_ceに発行年に関する列(year)を追加
df_ce["year"] = pd.to_datetime(df_ce["date"]).dt.year
# mcname(マンガ雑誌名)、year(発行年)別にユニークなmiid(雑誌巻号)数を集計
df_plot = df_ce.groupby(["mcname", "year"])["miid"].nunique().reset_index()
Show code cell content
# 可視化対象のDataFrameの冒頭5行を表示
df_plot.head()
| mcname | year | miid | |
|---|---|---|---|
| 0 | 週刊少年サンデー | 1970 | 21 |
| 1 | 週刊少年サンデー | 1971 | 51 |
| 2 | 週刊少年サンデー | 1972 | 51 |
| 3 | 週刊少年サンデー | 1973 | 51 |
| 4 | 週刊少年サンデー | 1974 | 50 |
Show code cell source
# mcnameが週刊少年サンデーと一致するデータのみ抽出し、インデックスを張り直す
df_sunday = df_plot[df_plot["mcname"] == "週刊少年サンデー"].reset_index(drop=True)
# go.Scatterで散布図オブジェクトを作成
# x軸として週刊少年サンデーの発売年、y軸として週刊少年サンデーの年間巻号数
trace = go.Scatter(x=df_sunday["year"], y=df_sunday["miid"], name="週刊少年サンデー")
# figとしてFigureクラスのインスタンスを初期化
# このとき、先に定義したtraceをdataとして渡す
fig = go.Figure(data=trace)
# figを表示
show_fig(fig)
Show code cell source
# df_plotデータフレームを"mcname"カラムでグループ化し、各グループに対して処理を実行
for mcname, df_mc in df_plot.groupby("mcname"):
# もしグループの名前が"週刊少年サンデー"の場合は、既に追加済みなのでスキップ
if mcname == "週刊少年サンデー":
continue
# グループ化されたデータに対して散布図のトレースを作成
# x軸には"year"カラムのデータ、y軸には"miid"カラムのデータを使用
# トレースの名前はmcname(マンガ雑誌名)に設定
trace_mc = go.Scatter(x=df_mc["year"], y=df_mc["miid"], name=mcname)
# 作成したトレースを図figに追加
fig.add_trace(trace_mc)
# 最終的に作成した図を表示
show_fig(fig)
Show code cell source
# update_tracesメソッドを用いて、マーカーを追加し、そのサイズを10に指定
fig.update_traces(mode="lines+markers", marker=dict(size=10))
# 再度figを表示
show_fig(fig)
layout: グラフの配置やスタイル#
Show code cell source
# figのlayoutを更新して、x軸とy軸にタイトルを設定
fig.update_layout(xaxis={"title": "発売年"}, yaxis={"title": "年間巻号数"})
# layout更新済みのfigを再表示
show_fig(fig)
plotly.expressによる可視化#
Show code cell content
# plotly.expressをpxとしてインポート
import plotly.express as px
グラフの作成#
Show code cell source
# px.lineを使用して、df_plotデータフレームから折れ線グラフを作成
# x軸には"year"カラムのデータを、y軸には"miid"カラムのデータを使用
# "mcname"カラムの値に基づいて、異なる線の色分けを行う
fig = px.line(df_plot, x="year", y="miid", color="mcname")
# 作成した線グラフを表示
show_fig(fig)
グラフの調整#
Show code cell source
# update_tracesメソッドを用いて、マーカーを追加し、そのサイズを10に指定
fig.update_traces(mode="lines+markers", marker=dict(size=10))
# figのlayoutを更新して、x軸とy軸にタイトルを変更
fig.update_layout(xaxis={"title": "発売年"}, yaxis={"title": "年間巻号数"})
# 更新済みのfigを再表示
show_fig(fig)
高度なグラフの作成#
Show code cell source
# px.lineを使用して、df_plotデータフレームから折れ線グラフを作成
# x軸には"year"カラムのデータを、y軸には"miid"カラムのデータを使用
# "mcname"カラムの値に基づいて、facetを2列で折り返して表示する
fig = px.line(df_plot, x="year", y="miid", facet_col="mcname", facet_col_wrap=2)
# 作成した線グラフを表示
show_fig(fig)