首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用单选按钮显示Bokeh多个图例

Bokeh是一个Python的交互式数据可视化库,可以用于创建各种类型的图形,包括折线图、散点图、柱状图等。在Bokeh中,我们可以使用单选按钮来显示多个图例,可以通过以下步骤实现:

  1. 导入必要的库和模块:
代码语言:txt
复制
from bokeh.plotting import figure, show
from bokeh.models import RadioButtonGroup, CustomJS
from bokeh.layouts import column
  1. 创建一个包含图形的figure对象:
代码语言:txt
复制
p = figure(plot_width=400, plot_height=400)
  1. 定义不同的数据和图例:
代码语言:txt
复制
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 3, 2, 5]
y2 = [3, 2, 1, 4, 2]
  1. 绘制初始的图形:
代码语言:txt
复制
p.line(x, y1, line_color="red", legend_label="Line 1")
p.circle(x, y1, fill_color="red", line_color="red", size=8)

p.line(x, y2, line_color="blue", legend_label="Line 2")
p.circle(x, y2, fill_color="blue", line_color="blue", size=8)
  1. 创建单选按钮组件:
代码语言:txt
复制
radio_button_group = RadioButtonGroup(labels=["Line 1", "Line 2"], active=0)

其中,labels参数用于指定单选按钮的显示文本,active参数用于指定默认选中的按钮索引。

  1. 创建一个JavaScript回调函数,用于根据选择的按钮索引显示对应的图例:
代码语言:txt
复制
callback = CustomJS(args=dict(renderer=p), code="""
    var index = cb_obj.active;
    if (index == 0) {
        renderer.legend[0].visible = true;
        renderer.legend[1].visible = false;
    } else {
        renderer.legend[0].visible = false;
        renderer.legend[1].visible = true;
    }
""")
  1. 将回调函数绑定到单选按钮组件上:
代码语言:txt
复制
radio_button_group.js_on_change('active', callback)
  1. 创建布局,将图形和单选按钮组件组合在一起:
代码语言:txt
复制
layout = column(p, radio_button_group)
  1. 显示布局:
代码语言:txt
复制
show(layout)

这样,你就可以通过选择单选按钮来显示不同的图例了。对于Bokeh多个图例的显示,目前Bokeh并没有提供直接的API来处理,但可以通过设置图例的visible属性来实现显示和隐藏。

推荐的腾讯云相关产品:腾讯云服务器(CVM)、云数据库MySQL版(CDB)等。你可以在腾讯云官方网站查找更多详细信息和产品介绍。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

  • 领券