如何在 Python Plotly 中將組中的所有值在懸停時高亮顯示?


Plotly 具有對資料值進行分組的功能。您也可以在懸停時高亮顯示來自組的所有值。在本教程中,我們將使用plotly.io 生成圖形。它包含許多自定義圖表的方法。

請按照以下步驟在懸停時高亮顯示來自組的所有值。

步驟 1

匯入plotly.io 模組並將其別名為pio

import plotly.io as pio

步驟 2

建立一個值列表以形成字典。

fonts = ['Arial', 'Arial', 'Courier', 'Arial', 'Courier', 'Arial']
shade = ['bold','bold','italic','italic','bold','bold']
score = [1,2,3,4,5,6]

步驟 3

根據 X 和 Y 軸座標值建立散點圖,並應用groupby 為字型設定樣式,併為值字典設定樣式。

data = [dict(
   type = 'scatter',
   x = shade,
   y = score,
   mode = 'markers',
   transforms = [dict(
      type = 'groupby',
      groups = fonts,
      styles = [
         dict(target = 'Arial', value = dict(marker = dict(color = 'blue'))),
         dict(target = 'Courier', value = dict(marker =
         dict(color = 'red'))),
         dict(target = 'bold', value = dict(marker = dict(color = 'black'))),
         dict(target = 'italic', value = dict(marker =
         dict(color = 'green')))
      ]
   )]
)]

步驟 4

讓我們使用值字典生成圖形並繪製圖形。它定義如下:

fig_dict = dict(data=data)
pio.show(fig_dict, validate=False)

示例

以下是突出顯示組中所有值的完整程式碼:

import plotly.io as pio

fonts = ['Arial', 'Arial', 'Courier', 'Arial', 'Courier', 'Arial']
shade = ['bold','bold','italic','italic','bold','bold']
score = [1,2,3,4,5,6]

data = [dict(
   type = 'scatter',
   x = shade,
   y = score,
   mode = 'markers',
   transforms = [dict(
      type = 'groupby',
      groups = fonts,
      styles = [
         dict(target = 'Arial', value = dict(marker = dict(color = 'blue'))),
         dict(target = 'Courier', value = dict(marker =
         dict(color = 'red'))),
         dict(target = 'bold', value = dict(marker = dict(color = 'black'))),
         dict(target = 'italic', value = dict(marker =
         dict(color = 'green')))
      ]
   )]
)]

fig_dict = dict(data=data)
pio.show(fig_dict, validate=False)

輸出

它將在瀏覽器上顯示以下輸出:


觀察到,當您將滑鼠懸停在一個點上時,它將突出顯示其所有值。

更新於: 2022年10月7日

992 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告