我正在尝试创建一个交互式图表,显示样式多年来收到的评论总数 . 我希望能够选择要显示的样式 . 但是我的代码无法执行此操作,并且我的图例无法正确显示 . 我也有很多风格 . 如果您知道显示复选框的好方法,我们将不胜感激任何帮助 . 您可以在下面找到数据集和代码 .
数据:https://www.dropbox.com/s/h7jrpcaocvvb7j7/data.csv?dl=0
available_styles = list(popularity.label.unique())
p = figure(
plot_width=800,
plot_height=500,
title='Popularity of beer styles over time',
x_axis_label='Time',
y_axis_label='Total number of reviews',
x_axis_type='datetime')
legend_box = []
style_selection = CheckboxGroup(labels=available_styles, active=[0, 1])
styles_to_plot = [style_selection.labels[i] for i in style_selection.active]
for i, style in enumerate(styles_to_plot):
subset = popularity[popularity['label'] == style]
src = ColumnDataSource(subset)
color = Category20_16[i]
x = 'date'
y = 'cumsum'
l = p.line(source=src, x=x, y=y, color=color)
legend_box.append((style_name, [l]))
legend = Legend(items=legend_box)
p.add_layout(legend, 'right')
legend.click_policy = 'hide'
#p.add_layout(legend, 'right')
def update(attr, old, new):
styles_to_plot = [
style_selection.labels[i] for i in style_selection.active
]
new_styles_to_plot = popularity[popularity['label'] == style]
src.data.update(new_styles_to_plot.data)
legend_box = []
style_selection.on_change('active', update)
# Interactivity
h = HoverTool(tooltips=[
('Date', '@date_hover'),
('Number of reviews', '@cumsum'),
('Beer Style', '@label'),
])
p.add_tools(h)
# Title
p.title.align = 'center'
p.title.text_font_size = '20pt'
p.title.text_font = 'serif'
# Axis titles
p.xaxis.axis_label_text_font_size = '14pt'
p.xaxis.axis_label_text_font_style = 'bold'
p.yaxis.axis_label_text_font_size = '14pt'
p.yaxis.axis_label_text_font_style = 'bold'
# Tick labels
p.xaxis.major_label_text_font_size = '12pt'
p.yaxis.major_label_text_font_size = '12pt'
# Show plot
layout = row(controls, p)
output_notebook()
show(layout)