Python 散景 - 交互式图例隐藏字形 - 不工作

Python Bokeh - interactive legend hiding glyphs - not working

我尝试实现 Bokeh 交互式图例,以根据用户选择过滤绘制的数据。我需要一些帮助来弄清楚我的代码有什么问题;我得到了每次使用的一些字形,不同的颜色(见下图)。

#Import libraries
from bokeh.io import output_notebook, show
from bokeh.models.sources import ColumnDataSource
from bokeh.plotting import figure
from bokeh.palettes import Category20_20
import pandas as pd

output_notebook()
#Create the dataframe
df = pd.DataFrame({'Index': ['9', '10', '11', '12', '13'],
        'Size': ['25', '15', '28', '43', '18'], 
        'X': ['751', '673', '542', '362', '224'],
        'Y': ['758', '616', '287', '303', '297'],
        'User': ['u1', 'u1', 'u2', 'u2', 'u2'],
        'Location': ['A', 'B', 'C', 'C', 'D'], 
        })

# Create plot

p = figure(plot_width=450, plot_height=450)
p.title.text = 'Title....'

users=list(set(df['User']))
size=df['Size']
for data, name, color in zip(df, users, Category20_20):
    p.circle(x=df['X'], y=df['Y'], size=size, color=color, alpha=0.8, legend=name)

p.legend.location = "top_left"
p.legend.click_policy="hide"

show(p)

在这个循环中

for data, name, color in zip(df, users, Category20_20):
    p.circle(x=df['X'], y=df['Y'], size=size, color=color, alpha=0.8, legend=name)

你是:

  • 迭代数据框的列名(因为Pandas在这方面很混乱),所以你的点数将受到限制(因为zip停在最短的集合)
  • 不使用data
  • 完整数据传递给p.circle,这意味着您有两组坐标和大小完全相同的圆
  • 使用已弃用的 legend 关键字

相反,试试这个:

users=list(set(df['User']))
for name, color in zip(users, Category20_20):
    user_df = df[df['User'] == name]
    p.circle(x=user_df['X'], y=user_df['Y'], size=user_df['Size'],
             color=color, alpha=0.8, legend_label=name)