plotlyレイアウト応用編ではグラフの見せ方について実例を紹介しながら学べる講座になります。
本内容はplotlyチュートリアルにおけるHover Text and Formatting in Pythonの内容です。
hoverは浮かぶという意味があり、plotlyではグラフのプロットにカーソルを動かした際にデータの詳細(カスタマイズ可能)を表示させるオプションのことを指します。
コードの詳細は省きながら重要な部分のみ紹介するので、これからPlotlyを始める方には下記記事を事前に読んで理解してから本記事を読むことをおすすめします。
①hover_name、hover_dataの使い方
②hoverlabelのレイアウト変更
③plotly.graph_objects(go)のhovermodeについて
④hover_dataの応用的な使用方法
⑤plotly.graph_objects(go)を使う場合  
 ⇒hovertemplateの使い方
⑥fig.update_tracesで後からhover_dataを変更する
まずは必要なライブラリをインポートします。
今回の内容では以下のものを使います。
import plotly.express as px
import plotly.graph_objects as go
import numpy as npplotly_expressで用意されているgapminderの2007年のデータで絞ったものをdf_2007として可視化する例です。
px.scatterで散布図を指定してhover_name=”country”とすることでタイトルがcountryと表示されます。
hover_dataはhoverとしてポップ表示させるデータの中身を指定するもので[“country”,”pop”]とリスト形式で渡すことで、x軸の値/y軸の値に加えてcountryとpopのデータも表示されるようになります。
df_2007 = px.data.gapminder().query("year==2007")
fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", log_x=True,
                 hover_name="country", hover_data=["continent", "pop"])
fig.show()ここでは新しい内容としてfig.update_traces(mode=●●)、fig.update_layout(hoverlabel=dict(●●))の使い方についてです。
modeの種類
‘lines’, ‘markers’, ‘text’, ‘lines+markers’が使用できます
layoutではさらに詳細を設定することができ、dict(辞書型)として渡すことでbgcolorやfont_size、font_familyといった変更が可能です。
df = px.data.gapminder().query("continent=='Oceania'")
fig = px.line(df, x="year", y="lifeExp", color="country", title="Custom layout.hoverlabel formatting")
fig.update_traces(mode="markers+lines")
fig.update_layout(
    hoverlabel=dict(
        bgcolor="white",
        font_size=16,
        font_family="Rockwell"
    )
)
fig.show()fig.update_layout(hovermode=’●●’)でhovermodeを簡単に変更できます。
また、x unifiedのような便利なhoverイベントが使用できるので覚えて置いて損はないです。
実際にグラフにカーソルを当てて見てください。
modeの種類
‘x’, ‘y’, ‘closest’, False, ‘x unified’, ‘y unified’
t = np.linspace(0, 2 * np.pi, 100)
fig = go.Figure()
fig.add_trace(go.Scatter(x=t, y=np.sin(t), name='sin(t)'))
fig.add_trace(go.Scatter(x=t, y=np.cos(t), name='cost(t)'))
fig.update_layout(hovermode='x unified')
fig.show()hover_dataのいろいろな表現方法の例です。
df = px.data.iris()
fig = px.scatter(df, x='petal_length', y='sepal_length', facet_col='species', color='species',
                 hover_data={'species':False, # remove species from hover data
                             'sepal_length':':.2f', # customize hover for column of y attribute
                             'petal_width':True, # add other column, default formatting
                             'sepal_width':':.2f', # add other column, customized formatting
                             # data not in dataframe, default formatting
                             'suppl_1': np.random.random(len(df)),
                             # data not in dataframe, customized formatting
                             'suppl_2': (':.3f', np.random.random(len(df)))
                            })
fig.update_layout(height=300)
fig.show()hobertemplateを使えば自由に文字などを記入できます。
HTMLを知っている方には便利。
<br>タグも使えます。
fig = go.Figure(go.Scatter(
    x = [1,2,3,4,5],
    y = [2.02825,1.63728,6.83839,4.8485,4.73463],
    hovertemplate =
    '<i>Price</i>: $%{y:.2f}'+
    '<br><b>X</b>: %{x}<br>'+
    '<b>%{text}</b>',
    text = ['Custom text {}'.format(i + 1) for i in range(5)],
    showlegend = False))
fig.add_trace(go.Scatter(
    x = [1,2,3,4,5],
    y = [3.02825,2.63728,4.83839,3.8485,1.73463],
    hovertemplate = 'Price: %{y:$.2f}<extra></extra>',
    showlegend = False))
fig.update_layout(
    hoverlabel_align = 'right',
    title = "Set hover text with hovertemplate")
fig.show()⑥fig.update_tracesとhovertemplateの応用
最後はおまけです。
Europeのデータだけhovertemplate=Noneでhoverを消すこともできます。
fig.data[0].hovertemplateの中身は以下の通りです。
fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", log_x=True, color='continent'
                )
print("plotly express hovertemplate:", fig.data[0].hovertemplate)
fig.update_traces(hovertemplate='GDP: %{x} <br>Life Expectancy: %{y}') #
fig.update_traces(hovertemplate=None, selector={'name':'Europe'}) # revert to default hover
print("user_defined hovertemplate:", fig.data[0].hovertemplate)
fig.show()plotly express hovertemplate: continent=Asia<br>gdpPercap=%{x}<br>lifeExp=%{y}<extra></extra>
user_defined hovertemplate: GDP: %{x} <br>Life Expectancy: %{y}
↓Plotlyについて学べる数少ない参考書です。