Bokeh graphs and pandas dataframe groupby object

Bokeh is a nice library, helping python web developers to visualise your data in the browser. It is on good terms with pandas, the statistical and data manipulation package beloved by data scientists. It can source points from a dataframe object directly. Unfortunately, it can't get a result of a group by object directly to display it as multiple lines, yet. But no worries, with just a few lines of code you can convince it to draw you a nice multiline graph. Take a look at the code snippet below:

  1. from bokeh.plotting import figure
  2. from bokeh.palettes import Spectral11
  3. import itertools
  4.  
  5. grouped = df.groupby(by=["A"])
  6. p = figure(width=750, height=350, title="Plot thickens")
  7.  
  8. line_dash_styles = [[10, 0], [20, 1], [10, 1], [5, 1]]
  9. for group, color, line_dash in zip(grouped, itertools.cycle(Spectral11), itertools.cycle(line_dash_styles)):
  10. name, data = group
  11. p.line(source=data[["B", "C"]], x='B', y='C', color=color, legend=name, line_dash=line_dash)
Topic: 

Add new comment