自訂按鈕

Python 的 Plotly 資料視覺化入門

Alex Scriven

Data Scientist

自訂按鈕能做什麼?

 

自訂按鈕可以:

  • 更新圖表的資料或版面配置元素

    • 我們所有 update_layout() 的自訂都能放進按鈕裡!
  • 協助動畫(不在本課範圍內)

Python 的 Plotly 資料視覺化入門

Plotly 的自訂按鈕

透過 updatemenus 參數加入,並設定:

  • typebuttonsdropdown
    • 下拉選單稍後再介紹!
  • direction:按鈕方向
    • 按鈕可並排(left)或上下(down)擺放
  • x/y:按鈕位置(浮點數)
  • showactiveTrue/False 是否顯示被按下的 active(按鈕索引)。
    • 作用中按鈕是目前選取的那個。
  • buttonsbutton 物件的清單
Python 的 Plotly 資料視覺化入門

用按鈕切換圖形類型

$$

fig = px.bar(
      data_frame=revenues, 
    x='Industry', y='Revenue',
    color='Industry')
fig.show()

依產業的簡單長條圖

Python 的 Plotly 資料視覺化入門

按鈕設定

 

my_buttons = [

{'label': "Bar plot",
'method': "update",
'args': [{"type": "bar"}]},
{'label': "scatterplot",
'method': "update",
'args': [{"type": "scatter", 'mode': 'markers'}]}
]
Python 的 Plotly 資料視覺化入門

`args` 參數

Plotly 中最容易讓人困惑的部分之一!

  • 結構為:

[{dictionary to send to data}, {dictionary to send to layout}]

圖形內部結構

Python 的 Plotly 資料視覺化入門

用 args 更新版面配置

dir(fig.layout)

圖形版面配置元素

  • 'args' 更新任一參數
Python 的 Plotly 資料視覺化入門

用 args 更新資料

dir(fig.data[0])

資料內部結構

  • 有些很熟悉,之後也會派上用場
Python 的 Plotly 資料視覺化入門

按鈕互動性

$$

fig.update_layout({
  'updatemenus': [{'type': "buttons",

'direction': 'down', 'x': 1.3, 'y': 0.5,
'showactive': True, 'active': 0,
'buttons': my_buttons}] }) fig.show()

$$

按鈕

Python 的 Plotly 資料視覺化入門

一起來練習吧!

Python 的 Plotly 資料視覺化入門

Preparing Video For Download...