You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取CSV绘制Bokeh图表时遇ValueRange错误求助

解决Bokeh绘制柱状图时的ValueError: Unrecognized range input问题

我一眼就看出问题所在了——Bokeh的figure组件里,x_range参数对输入格式有明确要求:它需要的是分类值组成的字符串列表(或者FactorRange对象),但你传入的years是pandas的int64类型Series,而且是带索引的序列,这不符合Bokeh的预期,所以才会抛出那个错误。

你手动设置years = ["2010","2010","2010","2010"]能运行,核心原因就是这个列表里的元素是字符串类型,刚好匹配了Bokeh对分类轴范围的要求,哪怕值重复也没关系(Bokeh会自动提取唯一值作为轴刻度)。而你从CSV读取的年份是整数类型的Series,Bokeh没办法把它识别为有效的分类范围输入。

下面给你几个可行的解决方案:

方案1:将年份转为字符串列表作为分类范围

这是最直接的适配方法,把读取到的整数年份转成字符串,再提取成列表:

from bokeh.plotting import figure, output_file, show
import pandas

output_file("bars.html")
input = pandas.read_csv("csv/SampleData.csv")

# 将year列转为字符串类型,再转成列表
years = input["year"].astype(str).tolist()
numbers = input["amount"].tolist()

# x_range传入字符串列表
p = figure(x_range=years, plot_height=250, title="graph title", toolbar_location=None, tools="")
# 注意vbar的x参数要用转成字符串后的year列
p.vbar(x=input["year"].astype(str), top=numbers, width=0.9)

p.xgrid.grid_line_color = None
p.y_range.start = 0
show(p)

方案2:使用FactorRange明确指定分类范围

如果你需要更灵活的分类轴配置,可以用Bokeh的FactorRange对象:

from bokeh.plotting import figure, output_file, show
from bokeh.models import FactorRange
import pandas

output_file("bars.html")
input = pandas.read_csv("csv/SampleData.csv")

years = input["year"].astype(str).tolist()
numbers = input["amount"].tolist()

# 用FactorRange指定分类因子
p = figure(x_range=FactorRange(factors=years), plot_height=250, title="graph title", toolbar_location=None, tools="")
p.vbar(x=input["year"].astype(str), top=numbers, width=0.9)

p.xgrid.grid_line_color = None
p.y_range.start = 0
show(p)

方案3:改用线性数值轴(如果不需要分类轴)

如果你的年份是连续的数值,其实完全可以不用分类轴,让Bokeh自动生成线性x轴,这样就不用设置x_range了:

from bokeh.plotting import figure, output_file, show
import pandas

output_file("bars.html")
input = pandas.read_csv("csv/SampleData.csv")

years = input["year"]
numbers = input["amount"]

# 不设置x_range,Bokeh会自动生成线性x轴
p = figure(plot_height=250, title="graph title", toolbar_location=None, tools="")
p.vbar(x=years, top=numbers, width=0.9)

p.xgrid.grid_line_color = None
p.y_range.start = 0
show(p)

这几种方法都能解决你的问题,你可以根据自己的需求选择最合适的一种~

内容的提问来源于stack exchange,提问作者Daan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:22:40