Python / Pandas / Bokeh:用数据框中的图例绘制多条线
Python / Pandas / Bokeh: plotting multiple lines with legends from dataframe
我在 Pandas dataframe
中有数据,我正试图绘制成时间序列线图。
在绘制一条直线时,我已经能够使用 p.line
函数非常成功地做到这一点,确保我制作了 x_axis_type 'datetime'
.
为了绘制多条线,我尝试使用 p.multi_line
,效果很好,但我还需要一个图例,根据这个 post,无法向多线添加图例:
Leo 对上面 link 中问题的回答看起来很有希望,但我似乎无法弄清楚当数据来自数据框时如何应用它。
有人有什么建议吗?
好的,这似乎有效:
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)
我在 Pandas dataframe
中有数据,我正试图绘制成时间序列线图。
在绘制一条直线时,我已经能够使用 p.line
函数非常成功地做到这一点,确保我制作了 x_axis_type 'datetime'
.
为了绘制多条线,我尝试使用 p.multi_line
,效果很好,但我还需要一个图例,根据这个 post,无法向多线添加图例:
Leo 对上面 link 中问题的回答看起来很有希望,但我似乎无法弄清楚当数据来自数据框时如何应用它。
有人有什么建议吗?
好的,这似乎有效:
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)