使用bokeh中x坐标的数据帧索引绘制pandas数据帧

2024-06-06 06:37:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想准备一个使用ColumnDataSource的bokeh图。作为数据源的pandasDataFrame有一列和一个datetime索引:

enter image description here

如何指定x值应为索引。我试着省略了它,希望这是默认的,但没有成功:

enter image description here

有一个丑陋的解决方案,我只是将索引作为数据帧中的列复制,但我希望有一个更优雅的解决方案:

enter image description hereenter image description here


Tags: 数据datetimebokeh解决方案数据源省略pandasdataframecolumndatasource
3条回答

我通常重置索引,这会使索引成为一列。类似于你丑陋的解决方案。然后打印指定的列。

df.reset_index(inplace = True)

或者,您可以只引用列,在matplotlib中,默认情况下,它通常按您所需的方式使用索引。不确定它是否对你有用,但值得一试。

df["avg"].plot()

或者你可以尝试时间序列图方法?详情如下。

TimeSeries in Bokeh using a dataframe with index

问题是您必须指定哪个列应该是“x”列。如果未指定“x”值,则bokeh.plotting中的默认行为是尝试在ColumnDataSource中查找名为“x”的列(该列不存在)。

这里有一件棘手的事情,就是在pandas中使用命名索引('timeseries')。当您创建ColumnDataSource时,该名称会被继承,因此您的源可能看起来像:

ds = ColumnDataSource(df)
print(ds.data)
# the ts_n values would be the actual timestamps from the df
> {'timestamp': [ts_1, ts_2, ts_3, ts_4, ts_5], 'avg': [0.9, 0.8, 0.7, 0.8, 0.9]}

如果您使用:

p.line(source=ds, x='timestamps', y='avg')

您可以用通常的语法调用索引以从DF获取索引 作为:
p.line(x = df.index.values, y = df['values_for_y'])

相关问题 更多 >