【问题标题】:Python Bokeh - interactive legend hiding glyphs - not workingPython Bokeh - 隐藏字形的交互式图例 - 不起作用
【发布时间】:2020-05-26 10:32:23
【问题描述】:

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

【问题讨论】:

    标签: python bokeh legend interactive


    【解决方案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)
    

    你是:

    • 遍历数据框的列名(因为 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)
    

    【讨论】:

    • 谢谢你,尤金!它现在正在工作。我对legend_label 有疑问,出现错误...“AttributeError:Circle 的意外属性'legend_label',....”。当我使用图例而不是图例标签时没有错误。
    • 啊,您使用的是过时版本的 Bokeh。如果你愿意,你可以升级它并使用legend_label。如果没有,请继续使用legend
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2017-09-03
    • 1970-01-01
    相关资源
    最近更新 更多