[英]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.