2015-07-20 51 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