使用Bokeh绘制整个pandas DataFrame

10

我想使用 Bokeh 绘制整个 pandas DataFrame。也就是说,我正在寻找第三行的 Bokeh 等价物:

import pandas as pd
income_df = pd.read_csv("income_2013_dollars.csv", sep='\t', thousands=',')
income_df.plot(x="year")

目前有没有一种方法可以做到这一点,还是我必须分别传递每个y值?


你卡在哪个部分了?你没有说明你想要什么类型的图表,同时获取值很容易,可以作为数组或列表,df['y_col'].values 这可能是必要的,否则 df['y_col'].values.to_list() 将会给你一个列表。 - EdChum
2个回答

9

Bokeh项目维护者的提示:此答案涉及一个已过时和弃用的API,该API已经被Bokeh删除。有关使用现代和完全支持的Bokeh API创建条形图的信息,请参见其他问题/答案。


您可能会发现图表示例很有用:

https://github.com/bokeh/bokeh/tree/master/examples/charts

如果您需要一个条形图,则可以执行以下操作:

from bokeh.charts import Bar
Bar(income_df, notebook=True).show()  # assuming the index is corretly set on your df

您可能想使用类似的“Line”或“TimeSeries”对象 - 只需查看更多详细信息和更多配置的示例 - 例如添加标题、标签等。请注意,您可以使用其他输出方法 - 笔记本、文件或服务器。有关文档,请参见此处:http://docs.bokeh.org/en/latest/docs/user_guide/charts.html#generic-arguments
更新:(对于如何显示输出的混淆表示感到抱歉)。指定图表的显示类型的另一种替代方法是使用方法“output_notebook()”、“output_file("file.html")”、“output_server()”,然后使用show方法。例如:
from bokeh.charts import Bar
from bokeh.plotting import output_notebook, show
output_notebook()
bar = Bar(income_df)
show(bar)

然而,以下操作不能执行:

from bokeh.charts import Bar
from bokeh.plotting import output_notebook
output_notebook()
Bar(income_df).show()  # WILL GIVE YOU AN ERROR

这两种展示方法是不同的。

1
Sarah的回复非常准确,并已提供有用的细节。值得一提的是,> 0.8版本中已经添加了对output_notebook()、output_file()和output_server()的显式支持(以及许多其他改进),旨在减少Charts接口与其他Bokeh低级API之间的差异。 - Fabio Pliger
链接已过期。 - Soren
1
Bokeh图表已被弃用,并且没有关于该软件包的文档。我认为现在应该使用Bokeh plotting - 9769953

1
请查看此用户指南部分,以获取有关使用Pandas创建条形图的现代信息:

https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#pandas

例如:

from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show
from bokeh.sampledata.autompg import autompg as df
from bokeh.transform import factor_cmap
        
df.cyl = df.cyl.astype(str)
group = df.groupby('cyl')
    
source = ColumnDataSource(group)
    
cyl_cmap = factor_cmap('cyl', palette="Spectral5", factors=sorted(df.cyl.unique()))
    
p = figure(x_range=group, title="MPG by # Cylinders",
           toolbar_location=None, tools="")
    
p.vbar(x='cyl', top='mpg_mean', width=1, source=source,
       line_color=cyl_cmap, fill_color=cyl_cmap)
    
p.y_range.start = 0
p.xgrid.grid_line_color = None
p.xaxis.axis_label = "some stuff"
p.xaxis.major_label_orientation = 1.2
p.outline_line_color = None
    
show(p)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接