2015-07-20 53 views
12

我想给一张熊猫数据框给Bokeh绘制多行的折线图。 x轴应该是df.index,每个df.columns应该是一个单独的行。用散景和熊猫绘制多条线

这是我还是执意想做什么:

import pandas as pd 
import numpy as np 
from bokeh.plotting import figure, show 

toy_df = pd.DataFrame(data=np.random.rand(5,3), columns = ('a', 'b' ,'c'), index = pd.DatetimeIndex(start='01-01-2015',periods=5, freq='d')) 

p = figure(width=1200, height=900, x_axis_type="datetime") 
p.multi_line(df) 
show(p) 

但是,我得到的错误:

RuntimeError: Missing required glyph parameters: ys 

相反,我已经成功地做到这一点:

import pandas as pd 
import numpy as np 
from bokeh.plotting import figure, show 

toy_df = pd.DataFrame(data=np.random.rand(5,3), columns = ('a', 'b' ,'c'), index = pd.DatetimeIndex(start='01-01-2015',periods=5, freq='d')) 

ts_list_of_list = [] 
for i in range(0,len(toy_df.columns)): 
    ts_list_of_list.append(toy_df.index) 

vals_list_of_list = toy_df.values.T.tolist() 

p = figure(width=1200, height=900, x_axis_type="datetime") 
p.multi_line(ts_list_of_list, vals_list_of_list) 
show(p) 

那(无意地)完成这项工作,但它对所有3条线都使用相同的颜色,如下所示: enter image description here

问题:

1)我怎么能传递一个数据帧大熊猫对背景虚化的multi_line?

2)如果不能直接使用,我该如何处理数据帧数据,以便multi_line将创建每行不同的颜色?

在此先感谢

回答

19

您需要提供的颜色来multi_line列表。在你的榜样,你会做,这样的事情:

p.multi_line(ts_list_of_list, vals_list_of_list, line_color=['red', 'green', 'blue']) 

下面是做或多或少你最后有什么与你的第二个实例的一个更通用的修饰,但有一点更简洁,也许更Python :

import pandas as pd 
import numpy as np 
from bokeh.palettes import Spectral11 
from bokeh.plotting import figure, show, output_file 
output_file('temp.html') 

toy_df = pd.DataFrame(data=np.random.rand(5,3), columns = ('a', 'b' ,'c'), index = pd.DatetimeIndex(start='01-01-2015',periods=5, freq='d')) 

numlines=len(toy_df.columns) 
mypalette=Spectral11[0:numlines] 

p = figure(width=500, height=300, x_axis_type="datetime") 
p.multi_line(xs=[toy_df.index.values]*numlines, 
       ys=[toy_df[name].values for name in toy_df], 
       line_color=mypalette, 
       line_width=5) 
show(p) 

这将产生:

multi_line plot

+2

注意,使用multi_line用于绘制数据帧的列的一个严重的缺点是,它是不会轻易可以添加每个列的图例项。请参阅[本问答](http://stackoverflow.com/questions/31419388/bokeh-how-to-add-legend-to-figure-created-by-multi-line-method) – jhin

+0

是否可以添加悬停工具到这样一个数字? –

+0

@NicoleGoebel:这可能是有用的:http://stackoverflow.com/questions/31496628/in-bokeh-how-do-i-add-tooltips-to-a-timeseries-chart-hover-tool – bs123

1

你需要绘制时间序列图。这将允许您轻松插入图例。 TimeSeries属性可能位于bokeh._legacy_charts下。请看下面的例子位于:

http://bokeh.pydata.org/en/0.9.3/docs/user_guide/charts.html

+0

很好请参阅散景中提供的两个图表和它的文档都在不断发展!我打算很快再看一次。 – bs123