Боке несколько легенд, показывая с помощью радио кнопки - PullRequest
0 голосов
/ 11 февраля 2019

Несколько легенд отображаются, когда я использую Bokeh и переключатель для переключения между сюжетами.Как удалить старые легенды и показать только текущую активную легенду?

Я предоставляю упрощенный код, и я работаю с CategoryoricalColorMappers в полной версии, где цвета меняются в зависимости от факторов.Я пробовал legend.visible = False варианты безуспешно.

from bokeh.plotting import figure, show,reset_output
from bokeh.io import output_notebook, curdoc
from bokeh.models import ColumnDataSource, Range1d, LabelSet, Label,CustomJS,CategoricalColorMapper
from bokeh.layouts import row,widgetbox
from bokeh.models.widgets import CheckboxGroup, RadioGroup,RadioButtonGroup
import pandas as pd
import numpy as np


#create data
source_points = ColumnDataSource(dict(
                x=[1, 2, 1, 2, 1, 2,1,2],
                y=[1, 1, 2, 2, 3, 3,4,4],
                category=['hi', 'lo', 'hi', 'lo', 'hi', 'lo', 'hi', 'lo'],
                size=['big','small','big','small','big','small','big','small'],
                weight=['light','heavy','very heavy','light','heavy','very heavy','light','heavy'] ))

#create graph
p=figure(x_range=(0, 4), y_range=(0, 5))
p.square(x='x',y='y',source=source_points, legend='category')
p.legend.orientation = "horizontal"
p.legend.location = "top_left"

#Adding Radio button
radio = RadioButtonGroup(labels=['category','weight','size'], active=0)
inputs = widgetbox(radio)


#update plots

def update_plot(attrname, old, new):
    plt = radio.active
    print(plt)
# Generate the new curve

    if plt is 0:
        p.square(x='x',y='y',source=source_points, legend='category',color='blue')
        p.legend.orientation = "horizontal"
        p.legend.location = "top_left"  

    elif plt is 1:
        p.square(x='x',y='y',source=source_points, legend='weight',color='blue')
        p.legend.orientation = "horizontal"
        p.legend.location = "top_left"  

    else:
        p.square(x='x',y='y',source=source_points, legend='size',color='black')
        p.legend.orientation = "horizontal"
        p.legend.location = "top_left"        

# event and function linkage
radio.on_change('active', update_plot)

#link everything together
curdoc().add_root(row(inputs, p, width=800))

Я хочу показать только активную легенду и скрыть / удалить старую легенду.Любой совет / помощь в вопросе легенды боке приветствуется?

1 Ответ

0 голосов
/ 12 февраля 2019

Вместо того, чтобы снова строить прямоугольник, вы должны обновить ColumnDataSource, используемый для построения прямоугольников.Вы можете сделать это, отредактировав словарь source.data.

#!/usr/bin/python3
from bokeh.plotting import figure, show
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.layouts import row, widgetbox
from bokeh.models.widgets import CheckboxGroup, RadioButtonGroup
from bokeh.transform import factor_cmap
from bokeh.palettes import Spectral7

#create data
source_points = ColumnDataSource(dict(
                x=[1, 2, 1, 2, 1, 2,1,2],
                y=[1, 1, 2, 2, 3, 3,4,4],
                legend=['hi', 'lo', 'hi', 'lo', 'hi', 'lo', 'hi', 'lo'],
                category=['hi', 'lo', 'hi', 'lo', 'hi', 'lo', 'hi', 'lo'],
                size=['big','small','big','small','big','small','big','small'],
                weight=['light','heavy','very heavy','light','heavy','very heavy','light','heavy']))

legend=list(set(source_points.data['category'] + source_points.data['size'] + source_points.data['weight']))

#create graph
p=figure(x_range=(0, 4), y_range=(0, 5))
p.square(x='x',y='y',source=source_points, legend='legend', color=factor_cmap('legend', palette=Spectral7, factors=legend))
p.legend.orientation = "horizontal"
p.legend.location = "top_left"

#Adding Radio button
radio = RadioButtonGroup(labels=['category','weight','size'], active=0)
inputs = widgetbox(radio)

#update plots
def update_plot(attrname, old, new):
    plt = radio.active
    newSource = source_points.data
    if radio.active is 0:
        newSource['legend'] = newSource['category']
    elif radio.active is 1:
        newSource['legend'] = newSource['weight']
    else:
        newSource['legend'] = newSource['size']
    source_points.data = newSource

# event and function linkage
radio.on_change('active', update_plot)

#link everything together
curdoc().add_root(row(inputs, p, width=800))
...