import plotly
import plotly.graph_objects as go
tips = plotly.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 |
# ❶ 曜日ごとのデータを抽出
tips_by_day = tips.groupby("day") # day列でグループ化
days = ["Thur", "Fri", "Sat", "Sun"]
# グループ化された各DataFrameを抽出
thur, fri, sat, sun = [tips_by_day.get_group(day) for day in days]
box_fig = go.Figure()
box_fig.add_trace(go.Box(y=thur["tip"], name="Thur"))
box_fig.add_trace(go.Box(y=fri["tip"], name="Fri"))
box_fig.add_trace(go.Box(y=sat["tip"], name="Sat"))
box_fig.add_trace(go.Box(y=sun["tip"], name="Sun"))
box_fig.show()
from plotly.subplots import make_subplots
violin_fig = make_subplots(rows=1, cols=2)
# ❶ 1列目のサブプロット
violin_fig.add_trace(
go.Violin(
y=thur["tip"],
name="Thur",
box_visible=True, # ❸ 箱ひげ図を重ねて描画
),
row=1,
col=1,
)
violin_fig.add_trace(
go.Violin(y=fri["tip"], name="Fri", box_visible=True), row=1, col=1
)
violin_fig.add_trace(
go.Violin(y=sat["tip"], name="Sat", box_visible=True), row=1, col=1
)
violin_fig.add_trace(
go.Violin(y=sun["tip"], name="Sun", box_visible=True), row=1, col=1
)
# ❷ 2列目のサブプロット
for data in thur, fri, sat, sun:
smoker = data.loc[data["smoker"] == "Yes"] # smoker列がYesのデータ
non_smoker = data.loc[data["smoker"] == "No"] # smoker列がNoのデータ
day = data["day"].iloc[0] # day列の先頭のデータ(ラベルに使用)
violin_fig.add_trace(
go.Violin(
x=smoker["day"],
y=smoker["tip"],
side="negative", # ❹ 左側に描画
name=f"{day}: somoker",
),
row=1,
col=2,
)
violin_fig.add_trace(
go.Violin(
x=non_smoker["day"],
y=non_smoker["tip"],
side="positive", # ❺ 右側に描画
name=f"{day}: non-somoker",
),
row=1,
col=2,
)
violin_fig.show()
import numpy as np
np.random.seed(1)
data0 = np.random.normal(10, 1, 10000)
data1 = np.random.normal(12, 1.5, 10000)
histogram_fig = make_subplots(rows=1, cols=2)
histogram_fig.add_trace(go.Histogram(x=data0, name="data0"), row=1, col=1)
histogram_fig.add_trace(go.Histogram(x=data1, name="data1"), row=1, col=1)
histogram_fig.add_trace(go.Histogram(y=data0, name="data0"), row=1, col=2)
histogram_fig.add_trace(
go.Histogram(
y=data1, # ❶ 引数yで横向き
name="data1",
nbinsy=50, # ❷ ビンの数を変更
),
row=1,
col=2,
)
histogram_fig.show()
go.Figure(
[go.Histogram(x=data0, name="data0"), go.Histogram(x=data1, name="data1")],
layout=go.Layout(barmode="stack"), # ❶ ヒストグラムを積み上げ
).show()
probability_comulative_histogram_fig = make_subplots(rows=1, cols=2)
probability_comulative_histogram_fig.add_trace(
go.Histogram(
x=data0,
# ❶ サンプル数の合計を1とした正規化
histnorm="probability",
name="probability",
),
row=1,
col=1,
)
probability_comulative_histogram_fig.add_trace(
go.Histogram(
x=data0,
# ❷ 累積ヒストグラム
cumulative={"enabled": True},
name="comulative",
),
row=1,
col=2,
)
probability_comulative_histogram_fig.show()
go.Figure(
go.Histogram(
x=data0,
# ❷ ヒストグラムの範囲を指定
xbins={"start": 8, "end": 11, "size": 0.01},
)
).show()
histogram2d_fig = make_subplots(rows=1, cols=2)
# ❶ 2次元ヒストグラム
histogram2d_fig.add_trace(go.Histogram2d(x=data0, y=data1), row=1, col=1)
# ❷ 等高線
histogram2d_fig.add_trace(
go.Histogram2dContour(x=data0, y=data1, showscale=False), row=1, col=2
)
histogram2d_fig.update_layout(coloraxis_showscale=False)
histogram2d_fig.show()
np.random.seed(1)
x = np.arange(1, 4)
y = np.random.rand(3)
err_value = np.random.rand(3) * 0.1
err_value_minus = np.random.rand(3) * 0.1
error_fig = make_subplots(rows=2, cols=2)
# ❶ エラーバーを一定の値で指定
error_fig.add_trace(
go.Scatter(
x=x,
y=y,
# エラーバーを定数で指定
error_y={"type": "constant", "value": 0.1},
),
row=1,
col=1,
)
# ❷ 各要素ごとにエラーバーを指定
error_fig.add_trace(
go.Scatter(
x=x,
y=y,
# 各要素のエラーバーを指定
error_x={"type": "data", "array": err_value},
),
row=1,
col=2,
)
# ❸ エラーバーを正の値と負の値をそれぞれ指定
error_fig.add_trace(
go.Bar(
x=x,
y=y,
error_y={
"symmetric": False, # エラーバーを非対称
"type": "data",
"array": err_value,
"arrayminus": err_value_minus, # 各要素の負の値を指定
},
),
row=2,
col=1,
)
error_fig.show()
iris = plotly.data.iris()
iris.head()
sepal_length | sepal_width | petal_length | petal_width | species | species_id | |
---|---|---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa | 1 |
1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa | 1 |
2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa | 1 |
3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa | 1 |
4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa | 1 |
go.Figure(
[
go.Parcoords(
dimensions=[
{"label": "sepal_length", "values": iris["sepal_length"]},
{"label": "sepal_width", "values": iris["sepal_width"]},
{"label": "petal_length", "values": iris["petal_length"]},
{"label": "petal_width", "values": iris["petal_width"]},
],
line={"color": iris["species_id"]}, # ❶ species_idで色分け
)
]
).show()
go.Figure(
[
go.Parcats(
dimensions=[
{"label": "sex", "values": tips["sex"]},
{"label": "smoker", "values": tips["smoker"]},
{"label": "day", "values": tips["day"]},
{"label": "time", "values": tips["time"]},
],
line={"color": tips["size"]}, # ❶ size列で色分け
)
]
).show()
import numpy as np
np.random.seed(1)
x = np.arange(0, 5)
y = np.arange(0, 50, 10)
z = np.random.randn(5, 5)
go.Figure([go.Heatmap(x=x, y=y, z=z)]).show()
go.Figure([go.Contour(x=x, y=y, z=z)]).show()
np.random.seed(7)
r1 = np.random.rand(6)
theta = np.linspace(0, 360, 7)[:-1]
r1_close = np.hstack([r1, np.array(r1[0])])
r2 = r1 + np.random.uniform(-0.3, 0.3, 6)
r2_close = np.hstack([r2, np.array(r2[0])])
label = list("abcdefa")
polar_fig = make_subplots(
rows=2,
cols=2,
specs=[
[{"type": "polar"}, {"type": "polar"}],
[{"type": "polar"}, {"type": "polar"}],
],
)
# ❶ 点で描画
polar_fig.add_trace(
go.Scatterpolar(r=r1, theta=theta, mode="markers"), row=1, col=1
)
# ❷ 線で描画(レーダチャート)
polar_fig.add_trace(
go.Scatterpolar(
r=r1_close, theta=label, mode="lines", fill="toself", name="r1"
),
row=1,
col=2,
)
polar_fig.add_trace(
go.Scatterpolar(
r=r2_close, theta=label, mode="lines", fill="toself", name="r2"
),
row=1,
col=2,
)
# ❸ 鶏頭図
polar_fig.add_trace(go.Barpolar(r=r1, theta=label), row=2, col=1)
polar_fig.add_trace(go.Barpolar(r=r2, theta=label), row=2, col=1)
polar_fig.show()
election = plotly.data.election()
election.head()
district | Coderre | Bergeron | Joly | total | winner | result | district_id | |
---|---|---|---|---|---|---|---|---|
0 | 101-Bois-de-Liesse | 2481 | 1829 | 3024 | 7334 | Joly | plurality | 101 |
1 | 102-Cap-Saint-Jacques | 2525 | 1163 | 2675 | 6363 | Joly | plurality | 102 |
2 | 11-Sault-au-Récollet | 3348 | 2770 | 2532 | 8650 | Coderre | plurality | 11 |
3 | 111-Mile-End | 1734 | 4782 | 2514 | 9030 | Bergeron | majority | 111 |
4 | 112-DeLorimier | 1770 | 5933 | 3044 | 10747 | Bergeron | majority | 112 |
scatterternary_trace = go.Scatterternary(
a=election["Bergeron"],
b=election["Coderre"],
c=election["Joly"],
mode="markers", # ❶
marker={"size": election["total"] * 1e-3}, # ❶
)
scatterternary_layout = go.Layout(
ternary={ # ❷
"aaxis": {"title": "Bergeron"}, # ❸
"baxis": {"title": "Coderre"}, # ❸
"caxis": {"title": "Joly"}, # ❸
}
)
go.Figure(scatterternary_trace, layout=scatterternary_layout)
import pandas as pd
stocks = plotly.data.stocks(indexed=True)
stocks.index = pd.to_datetime(stocks.index)
stocks.head()
company | GOOG | AAPL | AMZN | FB | NFLX | MSFT |
---|---|---|---|---|---|---|
date | ||||||
2018-01-01 | 1.000000 | 1.000000 | 1.000000 | 1.000000 | 1.000000 | 1.000000 |
2018-01-08 | 1.018172 | 1.011943 | 1.061881 | 0.959968 | 1.053526 | 1.015988 |
2018-01-15 | 1.032008 | 1.019771 | 1.053240 | 0.970243 | 1.049860 | 1.020524 |
2018-01-22 | 1.066783 | 0.980057 | 1.140676 | 1.016858 | 1.307681 | 1.066561 |
2018-01-29 | 1.008773 | 0.917143 | 1.163374 | 1.018357 | 1.273537 | 1.040708 |
ohlc_df = (
stocks["GOOG"]
.resample("1M") # 1週間ごとにリサンプル
.ohlc() # 4本値にリサンプル
)
go.Figure(
[
go.Candlestick(
x=ohlc_df.index,
open=ohlc_df["open"], # 始値
high=ohlc_df["high"], # 高値
low=ohlc_df["low"], # 安値
close=ohlc_df["close"], # 終値
)
]
).show()
go.Figure(
go.Waterfall(
x=[
"売上高",
"売上原価",
"売上総利益",
"販売費及び一般管理費",
"営業利益",
"営業外収益",
"営業外費用",
"経常利益",
"特別利益",
"特別損失",
"税引前当期純利益",
"法人税等",
"当期純利益",
],
measure=[
"relative",
"relative",
"total",
"relative",
"total",
"relative",
"relative",
"total",
"relative",
"relative",
"total",
"relative",
"total",
],
y=[1000, -300, 0, -150, 0, 100, -80, 0, 3, -5, 0, -100, 0],
)
).show()
funnel_fig = go.Figure()
funnel_fig.add_trace(
go.Funnel(
name="商品A",
y=["閲覧", "クリック", "カートに追加", "購入"],
x=[300, 150, 20, 18],
textinfo="percent initial", # ❶ 初期値からの変化
)
)
funnel_fig.add_trace(
go.Funnel(
name="商品B",
orientation="h",
y=["閲覧", "クリック", "カートに追加", "購入"],
x=[200, 40, 15, 13],
textinfo="label+percent previous", # ❶ 前の値からの変化
)
)
funnel_fig.show()
gapminder = plotly.data.gapminder()
gapminder_2007 = gapminder.loc[gapminder["year"] == 2007]
gapminder_2007.head()
country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
---|---|---|---|---|---|---|---|---|
11 | Afghanistan | Asia | 2007 | 43.828 | 31889923 | 974.580338 | AFG | 4 |
23 | Albania | Europe | 2007 | 76.423 | 3600523 | 5937.029526 | ALB | 8 |
35 | Algeria | Africa | 2007 | 72.301 | 33333216 | 6223.367465 | DZA | 12 |
47 | Angola | Africa | 2007 | 42.731 | 12420476 | 4797.231267 | AGO | 24 |
59 | Argentina | Americas | 2007 | 75.320 | 40301927 | 12779.379640 | ARG | 32 |
go.Figure(
[
go.Choropleth(
locations=gapminder_2007["country"], # ❶ 国名
locationmode="country names", # 位置データを国名で指定
z=gapminder["lifeExp"],
)
]
).show()
populations = np.array([38_505_000, 34_365_000, 28_125_000])
area = np.array([8_223, 3_367, 2_240])
lon, lat = [139.691711, 106.845131, 77.216667], [35.6, -6.214620, 28.666668]
text = ["Tokyo", "Jakarta", "Delhi"]
go.Figure(
[
go.Scattergeo(
lon=lon, # ❶ 経度
lat=lat, # ❶ 緯度
# ❷
marker={
"size": populations / 1_000_000, # 要素の大きさ
"color": populations / area, # 要素の色
"cmin": 1000, # 色の下限値
"cmax": 15000, # 色の上限値
# カラーバーを表示し、タイトルを指定
"colorbar": {"title": "人口密度"},
},
text=text, # ホバーツールに表示するテキスト
mode="markers", # 散布図として描画,
)
],
layout={"geo": {"scope": "asia"}},
).show()
go.Figure(
go.Scattergeo(
lon=lon + [-74.005966], # ❶ 経度
lat=lat + [40.714272], # ❶ 緯度
mode="lines", # ❷ 要素間を線で接続
text=text,
),
# ❸ 投影法を指定
layout={"geo": {"projection": {"type": "azimuthal equal area"}}},
).show()
import mapbox_env
mapbox_token = mapbox_env.token
go.Figure(
go.Scattermapbox(
lon=lon,
lat=lat,
text=text,
marker={
"size": populations / 1000000,
"color": populations / area,
"cmin": 1000,
"cmax": 15000,
"colorbar": {"title": "人口密度"},
},
),
layout={
# ❶ Mapboxインスタンス
"mapbox": go.layout.Mapbox(
accesstoken=mapbox_token, center={"lat": 19, "lon": 95}, zoom=2
)
},
).show()