[英]Python / Pandas / Bokeh: plotting multiple lines with legends from dataframe
我试图将Pandas dataframe
绘制到时间序列折线图中。
当绘制单条线时,我已经能够使用p.line
函数成功地做到这一点,确保将x_axis_type 'datetime'
。
要绘制多条线,我尝试使用p.multi_line
,效果很好,但我还需要一个图例,根据这篇文章,不可能在多线图中添加图例 : Bokeh如何在由multi_line创建的图形中添加图例方法?
Leo在上面的链接中对这个问题的回答看起来很有希望,但是当数据来自数据帧时,我似乎无法弄清楚如何应用它。
有人有提示吗?
好的,这似乎可行:
from bokeh.plotting import figure, output_file, save
from bokeh.models import ColumnDataSource
import pandas as pd
from pandas import HDFStore
from bokeh.palettes import Spectral11
# imports data to dataframe from our storage hdf5 file
# our index column has no name, so this is assigned a name so it can be
# referenced to for plotting
store = pd.HDFStore('<file location>')
df = pd.DataFrame(store['d1'])
df = df.rename_axis('Time')
#the number of columns is the number of lines that we will make
numlines = len(df.columns)
#import color pallet
mypalette = Spectral11[0:numlines]
# remove unwanted columns
col_list = ['Column A', 'Column B']
df = df[col_list]
# make a list of our columns
col = []
[col.append(i) for i in df.columns]
# make the figure,
p = figure(x_axis_type="datetime", title="<title>", width = 800, height = 450)
p.xaxis.axis_label = 'Date'
p.yaxis.axis_label = '<units>'
# loop through our columns and colours
for (columnnames, colore) in zip(col, mypalette):
p.line(df.index, df[columnnames], legend = columnnames, color = colore )
# creates an output file
output_file('<output location>')
#save the plot
save(p)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.