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

使用Bokeh绘制特斯拉股票图表时日期异常,图表显示混乱求助

Bokeh绘制特斯拉股票折线图显示混乱的问题解决

问题场景

我正在Jupyter Notebook中学习Bokeh库,使用以下代码绘制特斯拉股票收盘价随日期变化的折线图:

X=tesla['Date']
Y=tesla['Close']
output_file('time.html') #output file, have to import
fig=figure(width=2000, height=2000,title='Tesla Stock', toolbar_location="below",x_axis_type="datetime") #create figure object
fig.title.text="Tesla Stock"
fig.title.text_color="Gray"
fig.title.text_font="times"
fig.title.text_font_style="bold"
fig.xaxis.minor_tick_line_color='Red'
fig.yaxis.minor_tick_line_color='Blue'
fig.xaxis.axis_label="Date"
fig.yaxis.axis_label="Close"  
fig.line(X,Y) #fig (see import above), line graph and variables
show(fig)

但生成的图表显示混乱,请问哪里操作出错了?

问题原因

核心问题是**tesla['Date']列未被解析为datetime类型**,且数据可能未按日期排序:

  • Bokeh的x_axis_type="datetime"要求x轴数据必须是标准的datetime格式,如果Date列是字符串或其他非时间格式,Bokeh无法正确识别时间顺序,导致折线错乱。
  • 若原始数据的日期是乱序的,也会让折线图出现来回跳跃的混乱效果。

解决方案

  1. 将Date列转换为datetime类型,并对数据按日期排序
  2. 调整图表宽高为更合理的尺寸(2000x2000过大易导致显示变形)

修改后的代码如下:

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

# 转换日期格式并按日期排序
tesla['Date'] = pd.to_datetime(tesla['Date'])
tesla = tesla.sort_values('Date')

X = tesla['Date']
Y = tesla['Close']

output_file('time.html')
# 调整为更合理的宽高尺寸
fig = figure(width=1000, height=600, title='Tesla Stock', toolbar_location="below", x_axis_type="datetime")
fig.title.text = "Tesla Stock"
fig.title.text_color = "Gray"
fig.title.text_font = "times"
fig.title.text_font_style = "bold"
fig.xaxis.minor_tick_line_color = 'Red'
fig.yaxis.minor_tick_line_color = 'Blue'
fig.xaxis.axis_label = "Date"
fig.yaxis.axis_label = "Close"  
fig.line(X, Y)
show(fig)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:57:32