0

I have data in a Pandas dataframe that I am trying to plot to a time series line graph.

When plotting one single line, I have been able to do this quite successfully using the p.line function, ensuring I make the x_axis_type 'datetime'.

To plot multiple lines, I have tried using p.multi_line, which worked well but I also need a legend and, according to this post, it's not possible to add a legend to a multiline: Bokeh how to add legend to figure created by multi_line method?

Leo's answer to the question in the link above looks promising, but I can't seem to work out how to apply this when the data is sourced from a dataframe.

Does anyone have any tips?

2
  • could you give a bit more information on what you're trying to do exactly? In my experience with using bokeh and pandas, I just create a figure with fig = figure(), then I just loop through whatever data I'm using, creating a line with fig.line(x=x, y=y, legend="Label for this particular line") for each line I need. Then I just break out of the loop and show the figure, which then shows a single figure with multiple lines. Commented Nov 26, 2016 at 7:03
  • Thanks for your answer. I found some code elsewhere that does something very similar. Please see my own answer below. Commented Nov 26, 2016 at 15:30

1 Answer 1

3

OK, this seems to work:

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.