Python Bokeh-交互式图例隐藏字形-不起作用

问题描述 投票:0回答:1

我尝试实现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)

enter image description hereenter image description here

python bokeh legend interactive
1个回答
1
投票

在此循环中

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)

您是:

  • 迭代数据框的列名(因为熊猫在这方面非常令人困惑),所以您的点数将受到限制(因为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)
© www.soinside.com 2019 - 2024. All rights reserved.