Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python bokeh滑块未刷新绘图_Python_Data Visualization_Bokeh_Data Science - Fatal编程技术网

Python bokeh滑块未刷新绘图

Python bokeh滑块未刷新绘图,python,data-visualization,bokeh,data-science,Python,Data Visualization,Bokeh,Data Science,我正在创建一个带有滑块的bokeh绘图,以相应地刷新绘图。发布的代码有两个问题。 1.绘图不会按照滑块刷新。请帮助提供此问题的修复程序。 2.当使用bokeh serve--show fn.ipynb时,不使用curdoc()显示绘图 我正在尝试可视化CSV文件 import pandas as pd import numpy as np from bokeh.models import ColumnDataSource, CategoricalColorMapper, HoverTool, S

我正在创建一个带有滑块的bokeh绘图,以相应地刷新绘图。发布的代码有两个问题。 1.绘图不会按照滑块刷新。请帮助提供此问题的修复程序。 2.当使用
bokeh serve--show fn.ipynb
时,不使用
curdoc()
显示绘图

我正在尝试可视化CSV文件

import pandas as pd
import numpy as np
from bokeh.models import ColumnDataSource, CategoricalColorMapper, HoverTool, Slider
from bokeh.plotting import figure, curdoc
from bokeh.palettes import viridis
from bokeh.layouts import row, widgetbox

#Importing and processing data file 
crop = pd.read_csv('crop_production.csv') 

#Cleaning Data 
crop.fillna(np.NaN) 
crop['Season'] = crop.Season.str.strip() 

#Removing Whitespace #Filtering the dataset by Season 
crop_season = crop[crop.Season == 'Whole Year'] 
crop_dt = crop_season.groupby(['State_Name', 'District_Name', 'Crop_Year']).mean().round(1)

#Creating Column Data Source
source = ColumnDataSource({
        'x'        : crop_dt[crop_dt.index.get_level_values('Year')==2001].loc[(['ABC']), :].Area,
        'y'        : crop_dt[crop_dt.index.get_level_values('Year')==2001].loc[(['ABC']), :].Production,
        'state'    : crop_dt[crop_dt.index.get_level_values('Year')==2001].loc[(['ABC']), :].index.get_level_values('State_Name'),
        'district' : crop_dt[crop_dt.index.get_level_values('Year')==2001].loc[(['ABC']), :].index.get_level_values('District_Name')
})


#Creating color palette for plot
district_list = crop_dt.loc[(['Tamil Nadu']), :].index.get_level_values('District_Name').unique().tolist()
call_colors = viridis(len(district_list))
color_mapper = CategoricalColorMapper(factors=district_list, palette=call_colors)


# Creating the figure
#xmin, xmax = min(data.Crop_Year), max(data.Crop_Year)
#ymin, ymax = min(data.Production), max(data.Production)
p = figure(
    title = 'Crop Area vs Production',
    x_axis_label = 'Area',
    y_axis_label = 'Production',
    plot_height=900, 
    plot_width=1200,
    tools = [HoverTool(tooltips='@district')]
          )
p.circle(x='x', y='y', source=source, size=12, alpha=0.7, 
         color=dict(field='district', transform=color_mapper),
         legend='district')
p.legend.location = 'top_right'


def update_plot(attr, old, new):
    yr = slider.value
    new_data = {
        'x'        : crop_dt[crop_dt.index.get_level_values('Year')==yr].loc[(['ABC']), :].Area,
        'y'        : crop_dt[crop_dt.index.get_level_values('Year')==yr].loc[(['ABC']), :].Production,
        'state'    : crop_dt[crop_dt.index.get_level_values('Year')==yr].loc[(['ABC']), :].index.get_level_values('State_Name'),
        'district' : crop_dt[crop_dt.index.get_level_values('Year')==yr].loc[(['ABC']), :].index.get_level_values('District_Name')
    }
    source.data = new_data

#Creating Slider for Year
start_yr = min(crop_dt.index.get_level_values('Crop_Year'))
end_yr = max(crop_dt.index.get_level_values('Crop_Year'))
slider = Slider(start=start_yr, end=end_yr, step=1, value=start_yr, title='Year')
slider.on_change('value',update_plot)

layout = row(widgetbox(slider), p)
curdoc().add_root(layout)
show(layout)
还尝试了使用CustomJS的不同选项,如下所示,但仍然没有成功

callback = CustomJS(args=dict(source=source), code="""
    var data = source.data;
    var yr = slider.value;
    var x = data['x']
    var y = data['y']
    'x'        = crop_dt[crop_dt.index.get_level_values('Crop_Year')==yr].loc[(['ABC']), :].Area;
    'y'        = crop_dt[crop_dt.index.get_level_values('Crop_Year')==yr].loc[(['ABC']), :].Production;
    p.circle(x='x', y='y', source=source, size=12, alpha=0.7, 
         color=dict(field='district', transform=color_mapper),
         legend='district');
    }
    source.change.emit();
""")



#Creating Slider for Year
start_yr = min(crop_dt.index.get_level_values('Crop_Year'))
end_yr = max(crop_dt.index.get_level_values('Crop_Year'))
yr_slider = Slider(start=start_yr, end=end_yr, step=1, value=start_yr, title='Year', callback=callback)
callback.args["slider"] = yr_slider

在执行代码时遇到了很多问题,我做了一些更改,所以如果我做错了什么,请随时纠正我

该错误是由创建
列数据源
引起的,我必须将级别值更改为Crop_Year而不是Year。
loc'ABC'
也导致了一个错误,所以我也删除了这个错误(我必须添加
source=ColumnDataSource({
,您可能忘了复制它)

我还添加了一个下拉菜单,这样就可以只显示一个地区的数据

另外,我不太确定是否可以通过提供一个.ipynb文件来启动bokeh服务器,但请不要让我这么认为,我从不使用笔记本电脑。我已经用一个.py文件测试过了

#!/usr/bin/python3
import pandas as pd
import numpy as np
from bokeh.models import ColumnDataSource, CategoricalColorMapper, HoverTool
from bokeh.plotting import figure, curdoc
from bokeh.palettes import viridis
from bokeh.layouts import row, widgetbox
from bokeh.models.widgets import Select, Slider

#Importing and processing data file 
crop = pd.read_csv('crop_production.csv') 

#Cleaning Data 
crop.fillna(np.NaN) 
crop['Season'] = crop.Season.str.strip() 

#Removing Whitespace #Filtering the dataset by Season 
crop_season = crop[crop.Season == 'Whole Year'] 
crop_dt = crop_season.groupby(['State_Name', 'District_Name', 'Crop_Year']).mean().round(1)

crop_dt_year = crop_dt[crop_dt.index.get_level_values('Crop_Year')==2001]
crop_dt_year_state = crop_dt_year[crop_dt_year.index.get_level_values('State_Name')=='Tamil Nadu']

#Creating Column Data Source
source = ColumnDataSource({
    'x': crop_dt_year_state.Area.tolist(), 
    'y': crop_dt_year_state.Production.tolist(), 
    'state': crop_dt_year_state.index.get_level_values('State_Name').tolist(), 
    'district': crop_dt_year_state.index.get_level_values('District_Name').tolist()
})

#Creating color palette for plot
district_list = crop_dt.loc[(['Tamil Nadu']), :].index.get_level_values('District_Name').unique().tolist()
call_colors = viridis(len(district_list))
color_mapper = CategoricalColorMapper(factors=district_list, palette=call_colors)

# Creating the figure
p = figure(
    title = 'Crop Area vs Production',
    x_axis_label = 'Area',
    y_axis_label = 'Production',
    plot_height=900, 
    plot_width=1200,
    tools = [HoverTool(tooltips='@district')]
          )
glyphs = p.circle(x='x', y='y', source=source, size=12, alpha=0.7, 
         color=dict(field='district', transform=color_mapper),
         legend='district')
p.legend.location = 'top_right'

def update_plot(attr, old, new):
    #Update glyph locations
    yr = slider.value
    state  = select.value
    crop_dt_year = crop_dt[crop_dt.index.get_level_values('Crop_Year')==yr]
    crop_dt_year_state = crop_dt_year[crop_dt_year.index.get_level_values('State_Name')==state]
    new_data = {
        'x': crop_dt_year_state.Area.tolist(), 
        'y': crop_dt_year_state.Production.tolist(), 
        'state': crop_dt_year_state.index.get_level_values('State_Name').tolist(), 
        'district': crop_dt_year_state.index.get_level_values('District_Name').tolist()
    }
    source.data = new_data
    #Update colors
    district_list = crop_dt.loc[([state]), :].index.get_level_values('District_Name').unique().tolist()
    call_colors = viridis(len(district_list))
    color_mapper = CategoricalColorMapper(factors=district_list, palette=call_colors)
    glyphs.glyph.fill_color = dict(field='district', transform=color_mapper)
    glyphs.glyph.line_color = dict(field='district', transform=color_mapper)

#Creating Slider for Year
start_yr = min(crop_dt.index.get_level_values('Crop_Year'))
end_yr = max(crop_dt.index.get_level_values('Crop_Year'))
slider = Slider(start=start_yr, end=end_yr, step=1, value=start_yr, title='Year')
slider.on_change('value',update_plot)

#Creating drop down for state
options = list(set(crop_dt.index.get_level_values('State_Name').tolist()))
options.sort()
select = Select(title="State:", value="Tamil Nadu", options=options)
select.on_change('value', update_plot)

layout = row(widgetbox(slider, select), p)
curdoc().add_root(layout)

@Jasper非常感谢。这是有效的,但是它不适用于
.loc[(['Tamil Nadu']),:][/code>。这样做的原因是通过添加bokeh下拉列表或单选按钮对象来过滤数据,并根据过滤器刷新绘图。以下代码仅在
.loc[(['Tamil Nadu']),:]时有效
已删除。是否有其他方法解决此问题

def update_plot(attr, old, new):
    yr = slider.value
    new_data = {
        'x'        : crop_dt[crop_dt.index.get_level_values('Crop_Year')==yr].loc[(['Tamil Nadu']), :].Area.tolist(),
        'y'        : crop_dt[crop_dt.index.get_level_values('Crop_Year')==yr].loc[(['Tamil Nadu']), :].Production.tolist(),
        'state'    : crop_dt[crop_dt.index.get_level_values('Crop_Year')==yr].loc[(['Tamil Nadu']), :].index.get_level_values('State_Name').tolist(),
        'district' : crop_dt[crop_dt.index.get_level_values('Crop_Year')==yr].loc[(['Tamil Nadu']), :].index.get_level_values('District_Name').tolist()
    }
    source.data = new_data

你能在你的帖子中添加一些示例数据以便我们调试你的代码吗?我指的是crop_production.csv文件;)@Jasper添加数据和代码的初始部分:#导入和处理数据文件crop=pd.read#csv('crop_production.csv')#清理数据crop.fillna(np.NaN)crop['seash']=crop.seash.str.strip()#删除空白#按季节作物#季节=作物[作物.季节='全年']作物#dt=作物#季节过滤数据集。groupby(['州名称','地区名称','作物#年份])。平均值()我已经编辑了我的答案,以包含一个下拉列表以按状态筛选。它还没有更新颜色,但我今天没有时间修复。现在一切都应该修复。Din不希望得到这么多支持。我现在就要处理这个问题。但你已经完成了所有工作。非常感谢你的工作Jasper。很高兴为您服务!请使用复选标记在左边接受答案,如果这样可以的话。