如果我在X轴中使用字符串,则Python Bokeh绘图无法使用下拉菜单正确更新

2024-09-29 21:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试绘制数据,其中X轴为string,Y轴为int,并且有一个下拉列表来更改字符串以使用js回调更新Bokeh plot。如果我将X轴与字符串一起使用,它似乎不会很好地工作,但如果我更改为int(如year),它会正确地更新。下面是一个示例代码。我们将非常感谢您的帮助

数据集:

csv file

import pandas as pd
from bokeh.plotting import figure,output_file,show, save

from bokeh.io import output_notebook

from bokeh.models import NumeralTickFormatter,HoverTool,ColumnDataSource, CategoricalColorMapper,Select

from bokeh.transform import factor_cmap

from bokeh.models.widgets import Tabs,Panel

from bokeh.models import Slider, CustomJS

from bokeh.layouts import row,column

gap = pd.read_csv('Users/Downloads/gapminder_tidy.csv')
gap1 = gap.loc[:, ['Country', 'region', 'fertility']]
gap2 = gap1[gap1['Country'] == 'Iceland']
Overall = ColumnDataSource(data=gap1)
Curr = ColumnDataSource(data=gap2)
# plot and the menu is linked with each other by this callback function
callback = CustomJS(args=dict(source=Overall, sc=Curr), code="""
var f = cb_obj.value
sc.data['region']=[]
sc.data['fertility']=[]
for(var i = 0; i <= source.get_length(); i++){
    if (source.data['Country'][i] == f){
        sc.data['region'].push(source.data['Year'][i])
        sc.data['fertility'].push(source.data['fertility'][i])
     }
}
sc.change.emit();
""")
menu = Select(options=list(gap['Country'].unique()), value='Iceland', title='Country')  # drop down menu
p = figure(x_axis_label='region', y_axis_label='fertility')  # creating figure object
p.circle(x='region', top='fertility',bottom=0, color='green', source=Curr)  # plotting the data using glyph circle
menu.js_on_change('value', callback)  # calling the function on change of selection
layout = column(menu, p)  # creating the layout
show(layout)  # displaying the layout

Tags: csvthefromimportsourcedatabokehcountry

热门问题