こんな人にオススメ
plotly
でグラフを描くときのテンプレートを自分で作成するのが面倒。何か楽にキレイなグラフを描く方法はないの?
ということで、今回はplotly
でグラフを描く際に簡単にグラフの見た目、スタイルを変更する方法について解説する。どうするかというと、規定のテーマを選択するということ。
執筆者の場合は色んなこと対してカスタムすることが好きということで自作でテーマを作成している。しかし、それが面倒とかplotlyを始めたばかりという方もいるだろう。
そんな方は本記事で簡単にグラフのテーマを変更していただければ幸いだ。なお、自作テンプレートについては以下参照。
-
-
【随時更新 備忘録】plotlyのグラフ即席作成コード
続きを見る
python環境は以下。
- Python 3.9.4
- numpy 1.20.3
- plotly 4.14.3
- plotly-orca 3.4.2
下準備
import sys import numpy as np import plotly.io as pio import plotly.graph_objects as go sys.path.append('../../') import plotly_layout_template as template
まずは下準備としてのimport
関連。numpy
は後に作るグラフで使用するデータ作成用。plotly_layout_template
は本記事で作成するグラフとかのコードの2つ上のディレクトリにある、自作テンプレート。
今回はconfig
を追加するために使用。config
については以下参照。
-
-
【plotly&config】グラフのツールバーを編集する
続きを見る
plotly
のグラフテーマを知る
print(pio.templates) # Templates configuration # ----------------------- # Default template: 'plotly' # Available templates: # ['ggplot2', 'seaborn', 'simple_white', 'plotly', # 'plotly_white', 'plotly_dark', 'presentation', 'xgridoff', # 'ygridoff', 'gridon', 'none'] print(type(pio.templates)) # <class 'plotly.io._templates.TemplatesConfig'>
plotly
のグラフテーマはいくつか種類があって、どんなものがあるのかを確認するにはpio.templates
とすればいい。そうすると上のコードのようにズラーと出力される。
デフォルトのテーマはplotly
というもので、テンプレートを使用していない時に出てくる紫っぽい青っぽい背景のテーマだ。その他のテーマの選択肢は10種類ある。
テーマの値を取り出し
themes = pio.templates print(themes.items()) # dict_items([('ggplot2', <object object at 0x11702ad20>), ('seaborn', <object object at 0x11702ad20>), ('simple_white', <object object at 0x11702ad20>), ('plotly', <object object at 0x11702ad20>), ('plotly_white', <object object at 0x11702ad20>), ('plotly_dark', <object object at 0x11702ad20>), ('presentation', <object object at 0x11702ad20>), ('xgridoff', <object object at 0x11702ad20>), ('ygridoff', <object object at 0x11702ad20>), ('gridon', <object object at 0x11702ad20>), ('none', <object object at 0x11702ad20>)])
テーマはdict
っぽい感じで取り出すことが可能。上のコードではとりあえず.items
でkeys
とvalues
の両方出した。前半は先程のテーマ名だが後半は執筆者はあまり理解していない。出力するごとに数字部分の値が変わる。多分16進数だからメモリ関係か?
dict
っぽく扱うことができるということで、.keys
でテーマ名を取りだし。初めにpio.templates
で出力した使用可能なテーマ(Available templates
)が出力。
print(themes.keys()) # dict_keys(['ggplot2', 'seaborn', 'simple_white', 'plotly', 'plotly_white', 'plotly_dark', 'presentation', 'xgridoff', 'ygridoff', 'gridon', 'none'])
しかし、.values()
は使用できないようだ。あくまでもdict
っぽく扱うだけ。
print(themes.values()) # print(themes.values()) # AttributeError: 'TemplatesConfig' object has no attribute 'values'
dict
っぽく扱うことができるということで、最後に名称一覧list
で、各名称をfor
を使って1つずつ出力してみる。
print(list(themes)) # ['ggplot2', 'seaborn', 'simple_white', 'plotly', 'plotly_white', 'plotly_dark', 'presentation', 'xgridoff', 'ygridoff', 'gridon', 'none'] for theme in themes: print(theme) # ggplot2 # seaborn # simple_white # plotly # plotly_white # plotly_dark # presentation # xgridoff # ygridoff # gridon # none
各テーマをグラフ化
colors = ( 'white', 'silver', 'black', 'red', 'blue', 'green', 'yellow', 'violet', ) x = np.arange(5) y = x
ということでこれからテーマごとにグラフを作成するが、まずはグラフ関連の下準備。変数colors
は今回プロットするグラフの色を示す。色々な色のテーマを使用するので、プロットの色も豊富に。
今回プロットするデータは直線データで色ごとにズラしながら作成する。実際にテーマごとにグラフを作成するためのコードが以下。
# 各テーマを使用したグラフを作成 def plotly_themes(): for theme in themes: plot = [] for num, color in enumerate(colors): d = go.Scatter( x=x, y=y + num, name=color, line_color=color, ) plot.append(d) layout = go.Layout( template=theme, title=dict(text=theme), ) fig = go.Figure(data=plot, layout=layout) fig.show() name = f"plot_themes_{theme}" pio.write_html( fig, f"{name}.html", auto_open=False, config=template.plotly_config(), ) pio.write_image(fig, f"{name}.png") plotly_themes()
グラフのテーマはgo.Layout
のtemplate
引数で行う。ここに先程のpio.templates
を入れたら完了。以下よりそれぞれのテーマで作成できるグラフをプロットする。
ggplot2
seaborn
simple_white
plotly
plotly_white
plotly_dark
presentation
xgridoff
ygridoff
gridon
none
ボタンを使ってテーマを切り替えたい(失敗)
def plotly_themes_buttons(): plot = [] # for theme in themes: for num, color in enumerate(colors): d = go.Scatter( x=x, y=y + num, # name=f"{theme}|{color}", name=color, line_color=color, ) plot.append(d) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # ボタンの内容を作成 buttons = [] for num, theme in enumerate(themes): button = dict( label=theme, method='update', args=[ dict(), dict(title=theme, template=theme), ], ) buttons.append(button) updatemenus = [ dict( type='buttons', direction="right", x=0.5, y=1.01, xanchor='center', yanchor='bottom', active=0, buttons=buttons, ) ] # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - layout = go.Layout( template=theme, title=dict(text=theme), updatemenus=updatemenus, ) fig = go.Figure(data=plot, layout=layout) fig.show() name = 'plot_themes_buttons' pio.write_html( fig, f"{name}.html", auto_open=False, config=template.plotly_config(), ) pio.write_image(fig, f"{name}.png") plotly_themes_buttons()
最後にplotly
のボタン機能を使用してテーマを切り替える方法について解説したかった。が、どうもボタンを使って切り替えることができない。通常のgo.Layout
の引数ならこれでいけるけどなんか無理。
ということで失敗作が上のグラフ。ボタンについては以下参照。
-
-
【plotly&ボタン】plotlyのupdatemenusにbuttonsを追加
続きを見る
-
-
【plotly&ボタン】plotlyのupdatemenusに2回押し対応のbuttonsを追加
続きを見る
とっかかりには最適
今回はplotly
で使用できる既存のテーマについて解説した。これを知ったのは最近で、こんなに簡単にできるのかという印象。実はこのpio.templates
関連で自分でデフォルトテーマを作成することが可能らしい。
今回は既存テーマということでまだ勉強していないが、一回これはチャレンジしてみたい。
既存でそれなりにキレイなグラフを作成できるので、初めてのplotlyとかサクッとキレイにしたい人におオススメ。
関連記事
-
-
【plotly&go.Scatter】plotlyの散布図グラフの描き方
続きを見る
-
-
【plotly&バブルチャート】plotlyで各国の収入と平均寿命をバブルチャートで描く
続きを見る
-
-
【plotly&スライダー】plotlyのslidersにスライダーを追加
続きを見る
-
-
【plt vs plotly】matplotlibとgoでグラフの比較
続きを見る