使用散景中 x 坐标的数据帧索引绘制 pandas 数据帧
Plot a pandas dataframe using the dataframe index for x coordinate in bokeh
我想准备一个使用 ColumnDataSource
的散景图。作为数据源的 pandas
DataFrame
有一个列和一个 datetime
索引:
如何指定 x 值应该是索引。我试着省略它,希望这是默认设置,但它不起作用:
有一个丑陋的解决方案,我只是将索引复制为数据框中的一列,但我希望有一个更优雅的解决方案:
我通常会重置索引,这会使索引成为一列。类似于你丑陋的解决方案。然后绘制指定的列。
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'])
我想准备一个使用 ColumnDataSource
的散景图。作为数据源的 pandas
DataFrame
有一个列和一个 datetime
索引:
如何指定 x 值应该是索引。我试着省略它,希望这是默认设置,但它不起作用:
有一个丑陋的解决方案,我只是将索引复制为数据框中的一列,但我希望有一个更优雅的解决方案:
我通常会重置索引,这会使索引成为一列。类似于你丑陋的解决方案。然后绘制指定的列。
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'])