カテゴリー

当サイトはアフィリエイトプログラムによる収益を得ています〈景品表示法に基づく表記です)

px

【plotly&fill】px.areaで積み上げ塗りつぶし

2021年11月23日

こんな人にオススメ

pxで塗りつぶしをするのってどうやったらいい?goだと結構面倒だったけど簡単にできそう?

ということで、今回はpxpx.areaを使用してグラフの塗りつぶしを行う。以下の記事でmatplotlib.pyplotplt)とplotly.graph_objectsgo)での塗りつぶしを行った。

(9 < x y2)の条件に合った塗りつぶし
【plt&fill_between】matplotlibで領域を塗りつぶし

続きを見る

【plotly&fill】goで領域を塗りつぶし

続きを見る

pxはサクッとそれなりにグラフを作成できて便利。px.areaも例に漏れず簡単にグラフを作成することができる。

ただし、pxの場合は積み上げ式の塗りつぶししかできない。要するにstackオンリー。なぜ。

python環境は以下。

  • Python 3.10.1
  • matplotlib 3.5.1
  • plotly 5.4.0
  • plotly-orca 3.4.2

運営者のメガネです。YouTubeTwitterInstagram、自己紹介はこちら、お問い合わせはこちらから。

運営者メガネ

作成したコード全文

下準備(import

import matplotlib.cm as cm
import plotly
import plotly.express as px
import plotly.io as pio

まずは下準備としてのimport関連。基本はplotlyだけで話をすませるが、色付けをする際にplotlyだと使い勝手が悪い。ということでmatplotlib.cmのカラースケールを使用する。

また、カラースケールでmatplotlibを使用する際にplotlyの色の方式に合わせるためにplotlyimportしている。詳しくは後述する。

【plotly&色の自動調節】入力したRGBをrgba(R, G, B, a)に自動変換する

続きを見る

グラフはpxpx.areaで作成。グラフの保存はpioを使って行う。詳しくは以下の記事参照。

plotlyでグラフを静止画として保存する際に出るポップアップ
【plotly&orca】plotlyで静止画保存(orca)

続きを見る

単にpx.areaにすると意味のないグラフに


まずはシンプルにpx.areaで積み上げ式の塗りつぶしグラフを作成。指定するのはグラフ化したいデータの入ったデータフレームdfと、横軸x・縦軸yにしたいデータフレームの列名。

しかし、これらの引数だけでグラフを作成すると何が何やらわからんグラフになる。これだと意味のないグラフとなる。引数を追加して意味のあるグラフにする必要がある。

なお、fig.update_layoutでフォントサイズを大きくして見やすくしている。fig.updateシリーズについては以下の記事参照。

【plotly&fig作成と更新】add_traceやupdate_layoutの使い方

続きを見る

# シンプルにpx.areaにすると何が何やら

df = px.data.gapminder()
print(df)
#           country continent  year  ...   gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...  779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...  820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...  853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...  836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...  739.981106        AFG        4
# ...           ...       ...   ...  ...         ...        ...      ...
# 1699     Zimbabwe    Africa  1987  ...  706.157306        ZWE      716
# 1700     Zimbabwe    Africa  1992  ...  693.420786        ZWE      716
# 1701     Zimbabwe    Africa  1997  ...  792.449960        ZWE      716
# 1702     Zimbabwe    Africa  2002  ...  672.038623        ZWE      716
# 1703     Zimbabwe    Africa  2007  ...  469.709298        ZWE      716

# [1704 rows x 8 columns]

fig = px.area(
    df,  # 使用するデータフレーム
    x='year', y='pop',  # 横軸と縦軸の列名
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = ''  # 保存ファイル名の接頭辞
save_name = f"{prefix}_simple"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

colorで色分けしてもよくわからん


px.areaでは引数colorを用いることで色分けすることができるが、単に色分けするだけでは意味がない。さらに引数を追加して意味のあるグラフにする必要あり。

# 色分けしても何が何やら

df = px.data.gapminder()

fig = px.area(
    df, x='year', y='pop',
    color='continent',  # 大陸で色分けしてみる
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_simple_color"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

line_groupでデータ分け


引数line_groupにデータフレームの列名を指定することで、その列のデータで積み上げを分けてくれる。

上のグラフではline_group=’country’で国ごとに積み上げ式のグラフになるように設定した。これで積み上げ式のグラフになった。見づらいが。

# line_groupで国ごとのデータ分け

df = px.data.gapminder()
print(df)
#           country continent  year  ...   gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...  779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...  820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...  853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...  836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...  739.981106        AFG        4
# ...           ...       ...   ...  ...         ...        ...      ...
# 1699     Zimbabwe    Africa  1987  ...  706.157306        ZWE      716
# 1700     Zimbabwe    Africa  1992  ...  693.420786        ZWE      716
# 1701     Zimbabwe    Africa  1997  ...  792.449960        ZWE      716
# 1702     Zimbabwe    Africa  2002  ...  672.038623        ZWE      716
# 1703     Zimbabwe    Africa  2007  ...  469.709298        ZWE      716

# [1704 rows x 8 columns]

fig = px.area(
    df, x='year', y='pop',
    line_group='country',  # 国でデータ分けをする
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_line_group"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

line_groupcolorで色分け

color=’continent’で大陸ごとに色分け


ただ、line_groupを指定するだけだと、全ての積み上げが同じ色になってしまうのでグラフが見づらい。そこで最初に作成したシンプルなグラフで使った引数colorを使用。

color=’continent’にして大陸ごとに色を指定することで、大陸ごとの傾向を掴むことが可能に。

# 大陸ごとに色分け
df = px.data.gapminder()
print(df)
#           country continent  year  ...   gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...  779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...  820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...  853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...  836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...  739.981106        AFG        4
# ...           ...       ...   ...  ...         ...        ...      ...
# 1699     Zimbabwe    Africa  1987  ...  706.157306        ZWE      716
# 1700     Zimbabwe    Africa  1992  ...  693.420786        ZWE      716
# 1701     Zimbabwe    Africa  1997  ...  792.449960        ZWE      716
# 1702     Zimbabwe    Africa  2002  ...  672.038623        ZWE      716
# 1703     Zimbabwe    Africa  2007  ...  469.709298        ZWE      716

# [1704 rows x 8 columns]

# 大陸ごとに色分け
fig = px.area(
    df, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='continent',  # 大陸で色分け
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_color_continent"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

color='country'で国ごとに色分け


一方で、color='country'で国ごとに色分けすることも可能。だがしかし、デフォルトの色のセットの数は国数よりも少ない。そのため同じ色が繰り返し使用されてかなり見づらい。

次で解説するcolor_discrete_sequenceを使うことで色について深掘りする。

# 国ごとに色分け

df = px.data.gapminder()

fig = px.area(
    df, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='country',  # 国で色分け
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_color_country"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

color_discrete_sequenceで色を指定

plotlyのカラースケールを使用


引数color_discrete_sequenceを使うことでグラフの色を指定することが可能。ここではPlotly公式の「Built-in Continuous Color Scales in Python」よりpx.colors.sequential.Jetという、青から赤にかけてのカラースケールを使った。

んだが、実はPlotlyのカラースケールは用意されている色の数が極端に少ない。Jetだと以下に示すように6色しかない。

print(px.colors.sequential.Jet)
# ['rgb(0,0,131)', 'rgb(0,60,170)', 'rgb(5,255,255)', 'rgb(255,255,0)', 'rgb(250,0,0)', 'rgb(128,0,0)']

そのせいで上のグラフのように同じ色が繰り返し使用されるという始末に。これだと見づらいのに変わりなし。

次ではこの問題を解決するべく、matplotlibmatplotlib.cmを使用してカラースケールを自作する。

# px.colorsは色の数が少ないから、同じ色が繰り返される
df = px.data.gapminder()
print(df)
#           country continent  year  ...   gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...  779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...  820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...  853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...  836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...  739.981106        AFG        4
# ...           ...       ...   ...  ...         ...        ...      ...
# 1699     Zimbabwe    Africa  1987  ...  706.157306        ZWE      716
# 1700     Zimbabwe    Africa  1992  ...  693.420786        ZWE      716
# 1701     Zimbabwe    Africa  1997  ...  792.449960        ZWE      716
# 1702     Zimbabwe    Africa  2002  ...  672.038623        ZWE      716
# 1703     Zimbabwe    Africa  2007  ...  469.709298        ZWE      716

# [1704 rows x 8 columns]

# px.colors.sequential.Jetは6色しかない
# <https://plotly.com/python/builtin-colorscales/>
print(px.colors.sequential.Jet)
# ['rgb(0,0,131)', 'rgb(0,60,170)', 'rgb(5,255,255)', 'rgb(255,255,0)', 'rgb(250,0,0)', 'rgb(128,0,0)']

fig = px.area(
    df, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='country',  # 国で色分け
    color_discrete_sequence=px.colors.sequential.Jet,  # Jetでカラースケール指定
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_px_Jet"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

matplotlibのカラースケールを使用


plotlyのカラースケールだと色が繰り返し使用されて見づらかった。ここではmatplotlib.cmを使ってカラースケールを自作しつつグラフに反映させる。

今回は国ごとに色分けしたいので、cmでのカラースケール作成手順は以下のようにした。

  1. データフレームを上下逆(行を逆)にする
  2. 国一覧を変数として定義
  3. 各国に対してmatplotlib.cmで色を作成
  4. matplotlibの色をPlotlyの色に変換
  5. 文頭にrgbをつける
  6. 完成

1.の行を逆にするという処理はなくてもいいが、ない場合は積み上げの順番と凡例の順番が逆になったりして見づらい。どっちでもいい。

実際にカラースケールを自作してみる。まずはステップ1と2。データフレームの行を反転させるにはdf.iloc[::-1]とすれば良い。また、国一覧は一意な文字列にする必要があるからdf['country'].unique()とする。

# 作成するグラフを見やすくするために
# データフレームの上下(行)を反転させる
df = px.data.gapminder().iloc[::-1]
print(df)

# 国一覧
countries = df['country'].unique()

ステップ3-5では実際に色を作成。国一覧のcountriesの一国ずつ、cm.jetで色を作成する。cmのカラースケール一覧はmatplotlibの「Choosing Colormaps in Matplotlib」を参照。

cmでのカラースケールは、「各国の値 / 国の総数」で計算される0-1の数値で決まる。ただし、plotlyでは0-1ではなく0-255指定なので、plotly.colors.convert_to_RGB_255で0-255に変換している。plotly.colors.convert_to_RGB_255については「plotly.colors package」参照。

また、plotlyでは文頭にrgbもしくはrgbaaは不透明度、alpha)をつけないといけないので最後につけた。

あとはこれをpx.areaの引数color_discrete_sequenceに適用させるだけ。色の作成がややこしいけど、matplotlibで色作成→0-255へ変換→rgbをつけるだけだから慣れると簡単。

fig = px.area(
    df, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='country',  # 国で色分け
    color_discrete_sequence=colors,  # 作成したカラースケールを反映
)

# 凡例をアルファベット順に並べるために、凡例の順番を逆にする
fig.update_layout(legend_traceorder='reversed')
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_matplotlib_jet"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

dfの作成からグラフの保存までを一括で見たい方は以下にまとめたコードを載せたので参照いただきたい。

markerssymbolでプロットにマーカーを追加

markersでマーカーを追加


px.areaの引数markersを使うことでプロット線にマーカーを追加することが可能。これでマウスホバーで情報を見やすくなる。

markersはデフォルトではmarkers=Falseなので、markers=Trueと指定する必要がある。

# プロット点にマーカーをつける

# markersでマーカーを追加
df = px.data.gapminder()

fig = px.area(
    df, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='country',  # 国で色分け
    markers=True,  # マーカーを追加
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_markers"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

symbolでシンボルの形状を列指定


一方で、引数symbolを使うことでデータフレームの列名に応じてシンボルを変更することができる。例えば上のグラフだと国ごとにシンボルを変更している。

なお、全世界でグラフを作成するとデータ数が多くなるので、上のグラフだとdf.query('continent=="Asia"')でアジアの国に絞ってグラフを作成した。

df = px.data.gapminder()
# アジアだけ抽出
df_Asia = df.query('continent=="Asia"')
print(df_Asia)
#           country continent  year  ...    gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...   779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...   820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...   853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...   836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...   739.981106        AFG        4
# ...           ...       ...   ...  ...          ...        ...      ...
# 1675  Yemen, Rep.      Asia  1987  ...  1971.741538        YEM      887
# 1676  Yemen, Rep.      Asia  1992  ...  1879.496673        YEM      887
# 1677  Yemen, Rep.      Asia  1997  ...  2117.484526        YEM      887
# 1678  Yemen, Rep.      Asia  2002  ...  2234.820827        YEM      887
# 1679  Yemen, Rep.      Asia  2007  ...  2280.769906        YEM      887

# [396 rows x 8 columns]

fig = px.area(
    df_Asia, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='country',  # 国で色分け
    symbol='country'  # 国ごとにシンボルを変更
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_symbol"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

groupnormで積み上げ方法を変更

groupnorm=Noneで通常の積み上げ


引数groupnormを使用することで積み上げ方式を変更することが可能。積み上げ方式は以下の3種類から選択することができ、上のグラフはNone。これまでの積み上げと同じ。

  1. None: 単にデータを積み上げ
  2. fraction: 各値を総数で割り算=値は0-1の間になる
  3. percent: fraction のパーセント換算
# Noneで単にデータを積み上げ
df = px.data.gapminder()
print(df)
#           country continent  year  ...   gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...  779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...  820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...  853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...  836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...  739.981106        AFG        4
# ...           ...       ...   ...  ...         ...        ...      ...
# 1699     Zimbabwe    Africa  1987  ...  706.157306        ZWE      716
# 1700     Zimbabwe    Africa  1992  ...  693.420786        ZWE      716
# 1701     Zimbabwe    Africa  1997  ...  792.449960        ZWE      716
# 1702     Zimbabwe    Africa  2002  ...  672.038623        ZWE      716
# 1703     Zimbabwe    Africa  2007  ...  469.709298        ZWE      716

# [1704 rows x 8 columns]

# アジアだけ抽出
df_Asia = df.query('continent=="Asia"')
print(df_Asia)
#           country continent  year  ...    gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...   779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...   820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...   853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...   836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...   739.981106        AFG        4
# ...           ...       ...   ...  ...          ...        ...      ...
# 1675  Yemen, Rep.      Asia  1987  ...  1971.741538        YEM      887
# 1676  Yemen, Rep.      Asia  1992  ...  1879.496673        YEM      887
# 1677  Yemen, Rep.      Asia  1997  ...  2117.484526        YEM      887
# 1678  Yemen, Rep.      Asia  2002  ...  2234.820827        YEM      887
# 1679  Yemen, Rep.      Asia  2007  ...  2280.769906        YEM      887

# [396 rows x 8 columns]

fig = px.area(
    df_Asia, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='country',  # 色で色分け
    groupnorm=None,  # 単なるデータの積み上げ
    title='groupnorm = None'  # グラフタイトル
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_groupnorm_None"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

groupnorm=’fraction’で割合でグラフ化


groupnorm=’fraction’とすることで、各グラフが全体の中でどれくらいの割合なのかを0-1の値でグラフ化することが可能。なので最大値は1となる。

# fractionは各値を総数で割り算

df = px.data.gapminder()
# アジアだけ抽出
df_Asia = df.query('continent=="Asia"')

fig = px.area(
    df_Asia, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='country',  # 色で色分け
    groupnorm='fraction',  # データの積み上げ
    title="groupnorm = 'fraction'"  # グラフタイトル
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_groupnorm_fraction"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

groupnorm='percent'で100%換算


一方でgroupnorm='percent’とすることで100%換算することが可能。groupnorm='fractiont’の時と同じ考え方だが、違いは0-1にするか0%-100%にするか。

なので必ず0が下限値で100が上限値となる。

# percentはfractionのパーセント換算

df = px.data.gapminder()
# アジアだけ抽出
df_Asia = df.query('continent=="Asia"')

fig = px.area(
    df_Asia, x='year', y='pop',
    line_group='country',  # 国でデータ分け
    color='country',  # 色で色分け
    groupnorm='percent',  # データの積み上げ
    title="groupnorm = 'percent'"  # グラフタイトル
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_groupnorm_percent"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

orientationでグラフの描画向きを変更

orientation=’h’x, yがそのままならおかしなグラフ


引数orientation=’h’とすることで水平の積み上げ式グラフを作成することが可能。ただし、横軸・縦軸の関係が逆になるので引数x, yをデフォルト(orientation=’v’)のままにしているとグラフがバグる。

# orientationでグラフの描画向きを変更

# x, yの列名がorientation='v'(デフォルト)のままだと崩れる
df = px.data.gapminder()
print(df)
#           country continent  year  ...   gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...  779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...  820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...  853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...  836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...  739.981106        AFG        4
# ...           ...       ...   ...  ...         ...        ...      ...
# 1699     Zimbabwe    Africa  1987  ...  706.157306        ZWE      716
# 1700     Zimbabwe    Africa  1992  ...  693.420786        ZWE      716
# 1701     Zimbabwe    Africa  1997  ...  792.449960        ZWE      716
# 1702     Zimbabwe    Africa  2002  ...  672.038623        ZWE      716
# 1703     Zimbabwe    Africa  2007  ...  469.709298        ZWE      716

# [1704 rows x 8 columns]

fig = px.area(
    df, x='year', y='pop',
    line_group='country',  # 国でデータ分けをする
    color='continent',  # 大陸で色分け
    orientation='h',  # 水平にする
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_h_xy"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

x, yを逆にすると水平グラフとなる


orientation=’h’かつ引数x, yを逆にすると、横軸・縦軸が逆になった水平の積み上げ式グラフを作成できる。単に90度回転させたイメージ。

# x, yの列名を逆にする

df = px.data.gapminder()

fig = px.area(
    df,
    y='year', x='pop',  # x, yを逆にする
    line_group='country',  # 国でデータ分けをする
    color='continent',  # 大陸で色分け
    orientation='h',  # 水平にする
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_h_yx"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

facetでサブプロットを作成


引数facet_col, facet_rowを使用することで1つのグラフに複数のグラフを描けるサブプロットのようなグラフを作成することができる。facetに関しては以下の記事参照。

【px&facet】plotly.expressでsubplotsを描く

続きを見る

今回はcontinentごとに人口変化をグラフ化した。大陸は5つあるのでfacet_col_wrap=2で2列に並ぶように設定。余った右下の領域は自動で開けてくれる。なお、facet_col_wrapを指定しないと1列のグラフとなり見づらい。

df = px.data.gapminder()
print(df)
#           country continent  year  ...   gdpPercap  iso_alpha  iso_num
# 0     Afghanistan      Asia  1952  ...  779.445314        AFG        4
# 1     Afghanistan      Asia  1957  ...  820.853030        AFG        4
# 2     Afghanistan      Asia  1962  ...  853.100710        AFG        4
# 3     Afghanistan      Asia  1967  ...  836.197138        AFG        4
# 4     Afghanistan      Asia  1972  ...  739.981106        AFG        4
# ...           ...       ...   ...  ...         ...        ...      ...
# 1699     Zimbabwe    Africa  1987  ...  706.157306        ZWE      716
# 1700     Zimbabwe    Africa  1992  ...  693.420786        ZWE      716
# 1701     Zimbabwe    Africa  1997  ...  792.449960        ZWE      716
# 1702     Zimbabwe    Africa  2002  ...  672.038623        ZWE      716
# 1703     Zimbabwe    Africa  2007  ...  469.709298        ZWE      716

# [1704 rows x 8 columns]

fig = px.area(
    df, x='year', y='pop',
    line_group='country',  # 国でデータ分けをする
    color='country',  # 国で色分け
    facet_col='continent',  # 列の分割を大陸にする
    facet_col_wrap=2,  # 列数は2列にする
)
# グラフ全体とホバーのフォントサイズ変更
fig.update_layout(font_size=20, hoverlabel_font_size=20)
fig.show()

# グラフ保存
prefix = 'px-area'  # 保存ファイル名の接頭辞
save_name = f"{prefix}_facet"
pio.orca.config.executable = '/Applications/orca.app/Contents/MacOS/orca'
pio.write_html(fig, f"{save_name}.html")
pio.write_image(fig, f"{save_name}.png")

logで軸を対数表示