Python × 金融のコミュニティ
https://fin-py.connpass.com/event/186842/
https://quantopian-tokyo.connpass.com/event/187549/
2018年2月号 | SD別冊シリーズ | 2019年4月号 | 2020年2月号 |
---|---|---|---|
列名 | 説明 |
---|---|
country | 国名 |
continent | 大陸名 |
year | 年度 |
lifeExp | 寿命 |
pop | 人口 |
gdpPercap | 人口当りGDP |
import plotly.express as px
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 |
%matplotlib inline
gapminder.plot.scatter(x="gdpPercap", y="lifeExp", logx=True, xlim=[100, 1e6])
<matplotlib.axes._subplots.AxesSubplot at 0x7f588213f160>
Pythonやデータ処理とは全く違った分野の学習コストが発生
Pythonだけでできる!
px.scatter(
gapminder, x="gdpPercap", y="lifeExp", log_x=True,
color="continent", size="pop", size_max=40,
hover_name="country", # これだけ!
hover_data=["pop", "year"], # これだけ!
).show()
px.scatter(
gapminder,
x="gdpPercap", y="lifeExp", log_x=True,
size="pop", size_max=40, color="continent",
hover_name="country", hover_data=["pop"],
animation_frame="year", # これだけ!
).show()
gapminder_2007 = gapminder[gapminder["year"] == 2007]
px.sunburst(
gapminder_2007, path=["continent", "country"], values="pop", title="各国の人口"
).show()
px.treemap(gapminder_2007, path=["continent", "country"], values="pop", title="各国の人口").show()
tips = px.data.tips()
px.parallel_categories(
tips, dimensions=["sex", "smoker", "time", "day"], color="size"
).show()
時刻が5時のときだけコールバック関数が実行される(※ import文は省略)
def handler(callback):
while True:
if datetime.datetime.now().hour == 5:
callback()
time.sleep(360)
def callback():
print("5時です")
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# ❶ 引数にfigureを渡す
subplots_fig = go.FigureWidget(make_subplots(rows=1, cols=2))
subplots_fig.add_trace(
go.Scatter(
x=gapminder["gdpPercap"],
y=gapminder["lifeExp"],
text=gapminder["country"],
mode="markers",
name="散布図",
),
row=1,
col=1,
)
subplots_fig.add_trace(go.Scatter(name="時系列データ"), row=1, col=2)
trace0, trace1 = subplots_fig.data
title_text = "1人当りGDPと平均余命の散布図(左図)" "と平均余命の時系列データ(右図)"
subplots_fig.update_layout(title={"text": title_text})
# 軸ラベル
subplots_fig.update_xaxes(title="1人当りGDP", type="log", row=1, col=1)
subplots_fig.update_xaxes(title="年", row=1, col=2)
subplots_fig.update_yaxes(title="平均余命")
def update_line(trace, points, selector): # ❷
n = points.point_inds[0]
country = gapminder.iloc[n, 0] # ❸ インデックスから国名を取得
# ❸ countryから選択された国名のデータを抽出
country_df = gapminder.loc[gapminder["country"] == country].sort_values("year")
trace1.x = country_df["year"] # ❹
trace1.y = country_df["lifeExp"] # ❹
subplots_fig.update_layout( # ❺
annotations=[
{
"x": 1,
"y": 1.1,
"showarrow": False,
"text": country,
"xref": "paper",
"yref": "paper",
}
]
)
trace0.on_click(update_line)
subplots_fig
FigureWidget({ 'data': [{'mode': 'markers', 'name': '散布図', 'text': array(['Afg…
import dash
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
JupyterDash.infer_jupyter_proxy_config()
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
continents = gapminder["continent"].unique().tolist()
years = gapminder["year"].unique().tolist()
contries = gapminder.country.unique().tolist()
app.layout = html.Div(
[
html.Div(
[
dcc.Dropdown(
id="continent-dropdown",
options=[{"label": c, "value": c} for c in continents],
value=continents,
multi=True,
style={"textAlign": "center"},
),
dcc.Graph(id="scatter"),
dcc.Slider(
id="year-slider",
min=gapminder["year"].min(),
max=gapminder["year"].max(),
value=gapminder["year"].min(),
marks={str(year): str(year)[2:] for year in years},
step=None,
),
],
style={"width": "50%", "display": "inline-block", "verticalAlign": "top"},
),
html.Div(
[
dcc.Dropdown(
id="country-dropdown",
options=[{"value": contry, "label": contry} for contry in contries],
value=["Japan", "United States"],
multi=True,
),
dcc.Graph(id="line"),
],
style={"width": "50%", "display": "inline-block", "verticalAlign": "top"},
),
]
)
@app.callback(
Output("scatter", "figure"),
[Input("year-slider", "value"), Input("continent-dropdown", "value")],
)
def update_figure(selected_year, selected_continent):
filtered_df = gapminder[
(gapminder["year"] == selected_year)
& gapminder["continent"].isin(selected_continent)
]
if len(filtered_df) == 0:
fig = px.scatter()
else:
fig = px.scatter(
filtered_df,
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
hover_name="country",
log_x=True,
size_max=55,
)
fig.update_layout(transition_duration=500)
return fig
@app.callback(Output("line", "figure"), [Input("country-dropdown", "value")])
def update_graph(selected_country):
selected_gapminder = gapminder[gapminder["country"].isin(selected_country)]
return px.line(selected_gapminder, x="year", y="lifeExp", color="country")
app.run_server()
Dash app running on http://localhost:8888/proxy/8050/
app.run_server(mode="inline")
source: cytoscape_sample.py
パッケージの依存関係を可視化
ノードが移動できる
ノードを選択すると関係があるノードのスタイルが変更される
Pythonインタラクティブ・データビジュアライゼーション入門
―Plotly/Dashによるデータ可視化とWebアプリ構築―