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

使用Bokeh绘制图表失败求助:字符串格式月份轴无法正常工作

解决Bokeh中字符串类型月份X轴的散点图问题

嘿,我来帮你搞定这个问题!你遇到的情况是因为Bokeh默认处理字符串类型的轴时,不会自动识别月份的逻辑顺序,直接用字符串作为散点图的X值时,需要明确告诉Bokeh轴的分类顺序才能正常渲染。下面给你两种简单有效的解决方案:

方法1:将月份转换为有序分类变量

这种方法让Pandas和Bokeh都能识别月份的正确顺序,是更规范的做法:

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

# 读取数据
car = pd.read_csv('car_sales.csv')

# 定义月份的正确顺序
month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# 将Month列转换为有序分类
car['Month'] = pd.Categorical(car['Month'], categories=month_order, ordered=True)

Month = car['Month']
Sales = car['Sales']

output_file("bokeh_scatter_example.html", title="Bokeh Scatter Plot Example")
fig2 = figure(title="Bokeh Scatter Plot Example", x_axis_label='Month', y_axis_label='Sales')
fig2.circle(Month, Sales, size=5, alpha=0.5)
show(fig2)

方法2:直接在figure中指定X轴的顺序

如果你不想修改原始数据,可以在创建figure对象时,通过x_range参数直接传入月份的顺序列表:

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

car = pd.read_csv('car_sales.csv')
Month = car['Month']
Sales = car['Sales']

# 定义月份顺序
month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

output_file("bokeh_scatter_example.html", title="Bokeh Scatter Plot Example")
# 在figure中指定x_range为月份顺序
fig2 = figure(title="Bokeh Scatter Plot Example", x_axis_label='Month', y_axis_label='Sales', x_range=month_order)
fig2.circle(Month, Sales, size=5, alpha=0.5)
show(fig2)

为什么这两种方法有效?

当X轴是字符串类型时,Bokeh默认会按照字符串的字典序来排列轴标签,但月份的字典序和实际的时间顺序不一致(比如"Apr"会排在"Aug"前面,但实际4月在8月之前)。通过上述两种方法,我们明确告诉了Bokeh月份的正确顺序,这样不仅能让图表正常显示,还能保证X轴的顺序符合我们的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:38:00