用散景和 pandas 绘制多条线 [英] Plotting multiple lines with Bokeh and pandas
问题描述
我想给Bokeh一个熊猫数据框,以绘制多条折线图.
I would like to give a pandas dataframe to Bokeh to plot a line chart with multiple lines.
x轴应为df.index,每个df.columns应为单独的行.
The x-axis should be the df.index and each df.columns should be a separate line.
这就是我想做的:
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行使用相同的颜色,请参见下文:
That (ineligantly) does the job but it uses the same color for all 3 lines, see below:
问题:
1)如何将熊猫数据框传递到bokeh的multi_line?
2)如果无法直接实现,该如何处理数据框数据,以便multi_line将创建具有不同颜色的每一行?
谢谢.
推荐答案
您需要为multi_line提供颜色列表.在您的示例中,您将执行以下操作:
You need to provide a list of colors to multi_line. In your example, you would do, something like this:
p.multi_line(ts_list_of_list, vals_list_of_list, line_color=['red', 'green', 'blue'])
这是第二个示例的更通用的修改,它或多或少地完成了您最终得到的结果,但更加简洁一些,也许更像Python了:
Here's a more general purpose modification of your second example that does more or less what you ended up with, but is a little more concise and perhaps more Pythonic:
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)
产生:
这篇关于用散景和 pandas 绘制多条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!