"BokehUserWarning: ColumnDataSource's columns must be of the same length"

"BokehUserWarning: ColumnDataSource's columns must be of the same length"

我正在尝试绘制大量可追溯到 1998 年的数据。

我的代码似乎工作正常,但是当 运行 抛出错误消息时 "BokehUserWarning: ColumnDataSource's columns must be of the same length"

这是我的代码:

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

#Create dataframe
df = pd.read_csv('/Users/macbook/Desktop/source.tab', names=[
'#','datesent','total','place'] delimiter='\t', header=None, encoding="ISO-8859-1")

#Format date
df['datesent'] = pd.to_datetime(df['datesent'], dayfirst=True)

#Datamunging   
transactionssent = dict(pd.melt(df,value_vars=['datesent']).groupby('value').size())        
transactionssent_dataframe = pd.DataFrame.from_dict(transactionssent, orient= 'index')     
transactionssent_dataframe.columns = ['Number of sent transactions']                           
transactionssent_dataframe.index.rename('Date of sending', inplace= True)                         

#X- and Y-axis
x = pd.bdate_range('2017-1-1', '2200-1-1')
y = transactionssent_dataframe['Number of sent transactions']

#Bokeh object
ts = figure(x_axis_type="datetime")

#Show plot
ts.line(x, y)

output_file('/Users/macbook/Desktop/plot.html')

所有输出实际上都符合预期。错误是什么意思?我真的必须从数据框创建 ColumndDataSource 对象吗? 我认为将 pandas 数据帧直接传递给散景绘图函数是获得我想要的图形的好方法。是否有从 pandas 日期帧创建散景图的最佳做法?

我假设验证错误来自于您的 xy 系列的长度不同。如果有意义的话,输出可能会切断较长阵列的悬垂部分。

您不会 "have to" 手动创建一个 ColumnDataSource(一个是在您将数组传递给像 line 这样的字形方法时在内部创建的),但它有一些验证内容可以帮助防止这种情况.

您可以通过以下方式直接从数据框创建 ColumnDataSource:

source = ColumnDataSource(dataframe)
ts.line(x='x', y='y', source=source)

这个答案与问题没有直接关系,但指的是同一个警告: 如果您在交互式图中更改 ColumnDataSource 的长度,如果您逐步更改它,您将收到相同的警告,例如您的数据源是:

source = ColumnDataSource(
    data=dict(
        x=list(np.zeros(10)),
        y=list(np.ones(10)),
    )
)
p1 = plot.line(x='x', y='y', source=source, line_alpha=1, color="red")

并且您要更新的数据的长度为例如8. 你可以这样做:

p1.data_source.data['x'] = list(np.zeros(8))
p1.data_source.data['y'] = list(np.ones(8))

这将产生与上述相同的警告。 为避免警告,请使用字典设置值:

p1.data_source.data = {'x': list(np.zeros(8)),
                       'y': list(np.ones(8))}