import plotly.express as px
tips = px.data.tips()
tips.head()
total_bill | tip | sex | smoker | day | time | size | |
---|---|---|---|---|---|---|---|
0 | 16.99 | 1.01 | Female | No | Sun | Dinner | 2 |
1 | 10.34 | 1.66 | Male | No | Sun | Dinner | 3 |
2 | 21.01 | 3.50 | Male | No | Sun | Dinner | 3 |
3 | 23.68 | 3.31 | Male | No | Sun | Dinner | 2 |
4 | 24.59 | 3.61 | Female | No | Sun | Dinner | 4 |
px.scatter(
tips,
x="total_bill",
y="tip",
color="size", # size列で色分け
facet_row="time", # 縦に分割
facet_col="sex", # 横に分割
).show()
gapminder = px.data.gapminder()
gapminder.head()
country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
---|---|---|---|---|---|---|---|---|
0 | Afghanistan | Asia | 1952 | 28.801 | 8425333 | 779.445314 | AFG | 4 |
1 | Afghanistan | Asia | 1957 | 30.332 | 9240934 | 820.853030 | AFG | 4 |
2 | Afghanistan | Asia | 1962 | 31.997 | 10267083 | 853.100710 | AFG | 4 |
3 | Afghanistan | Asia | 1967 | 34.020 | 11537966 | 836.197138 | AFG | 4 |
4 | Afghanistan | Asia | 1972 | 36.088 | 13079460 | 739.981106 | AFG | 4 |
gapminder_fig = px.scatter(
gapminder,
x="gdpPercap",
y="lifeExp",
animation_frame="year", # アニメーションのためにデータを分割する列を指定
size="pop", # 要素の大きさを指定(バブルチャート)
color="continent", # 色分け
hover_name="country", # ホバーツールの名前
facet_col="continent", # 横に分割
log_x=True, # X軸を対数にとる
size_max=40, # 要素の大きさの最大値
width=800 # グラフの横幅
)
gapminder_fig.update_xaxes(tickfont={"size": 8}) # 軸目盛のフォントサイズ
gapminder_fig.show()
# figureを作成: 「2.3.2 figure による描画領域の作成」を参照
styled_fig = px.scatter(tips, x="total_bill", y="tip", facet_col="sex")
# traceを変更: 「2.4.6 update から始まるメソッドによる指定」を参照
# 「4.2.1 グラフのスタイル」を参照
styled_fig.update_traces(
marker={
"size": 10, # 要素のサイズ
"color": "lightblue", # 要素の色
"line": {"width": 2, "color": "slateblue"}, # 枠線のスタイル
},
row=1,
col=1,
)
styled_fig.update_traces(
marker={
"size": 10,
"color": "lightpink",
"line": {"width": 2, "color": "deeppink"},
},
row=1,
col=2,
)
# layoutを変更: 「2.4.6 update から始まるメソッドによる指定」を参照
# 「4.2.1 グラフのスタイル」を参照
styled_fig.update_layout(
width=800, # figureの幅
height=400, # figureの高さ
title={
"text": "総支払金額とチップの金額",
# グラフタイトルのスタイル
"font": {"family": "Courier", "size": 20, "color": "slategray"},
},
margin={"l": 20, "r": 20, "t": 40, "b": 20}, # 余白
paper_bgcolor="antiquewhite", # グラフ領域の背景色
)
styled_fig.update_xaxes(
ticks="outside", # 軸メモリを外側に表示
tickwidth=2, # 軸メモリの太さ
tickcolor="seagreen", # 軸メモリの色
ticklen=10, # 軸メモリの長さ
# X軸タイトル、フォントサイズ
title={"text": "総支払金額", "font": {"size": 10}},
)
styled_fig.update_yaxes(
ticks="outside",
tickwidth=2,
tickcolor="dimgray",
ticklen=10,
col=1,
title={"text": "チップの金額", "font": {"size": 10}},
)
styled_fig.show()