Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Bokeh: Set line color based on column in columndatasource

I'm trying to produce a chart that has multiple lines, but the data I use typically comes in long form like this:

x = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
y0 = [i**2 for i in x]
y1 = [10**i for i in x]
y2 = [10**(i**2) for i in x]
df = pandas.DataFrame(data=[x,y0,y1,y2]).T
df.columns = ['x','y0','y1','y2']

df2 = pd.concat([df.iloc[0:,1],df.iloc[0:,2],df.iloc[0:,3]], axis=0, keys = ['a','b','c']).reset_index()
df2.columns = ['grp','x','y']

df2

+----+-----+---+----------+
|    | grp | x |    y     |
+----+-----+---+----------+
|  0 | a   | 0 | 0.01     |
|  1 | a   | 1 | 0.25     |
|  2 | a   | 2 | 1.00     |
|  3 | a   | 3 | 2.25     |
|  4 | a   | 4 | 4.00     |
|  5 | a   | 5 | 6.25     |
|  6 | a   | 6 | 9.00     |
|  7 | b   | 0 | 1.26     |
|  8 | b   | 1 | 3.16     |
|  9 | b   | 2 | 10.00    |
| 10 | b   | 3 | 31.62    |
| 11 | b   | 4 | 100.00   |
| 12 | b   | 5 | 316.23   |
| 13 | b   | 6 | 1,000.00 |
+----+-----+---+----------+

cd_df2 = ColumnDataSource(df2)

That is to say, I'll have 'groups' where x,y pairs for each group are listed out across multiple rows.

The following produces all 3 lines, but they all show up as grey. Setting color = 'grp' does not specific a color for each value in the grp field in the columndata source

f = figure(tools="save",y_axis_type="log", y_range=[0.001, 10**11], 
       title="log axis example",x_axis_label='sections', y_axis_label=
       'particles')

f.line('x','y', line_color = 'grp', source = cd_df2)

How could I achieve this in the bokeh.plotting or bokeh.models api (want to avoid high level charts to better understand the library)? I'm open to other suggestions that avoid explicitly calling f.line() once for each line and individually set the color (I may have 10+ lines and this would get tedious).

like image 498
AllenQ Avatar asked Sep 18 '15 06:09

AllenQ


1 Answers

You can reuse the principle described in this example. It is based on "patches" but is the same for "line" (see http://docs.bokeh.org/en/latest/docs/reference/plotting.html):

p = figure()    
p.patches([x2 for a in areas], list(areas.values()), color=colors, alpha=0.8, line_color=None)
like image 53
PiWi Avatar answered Oct 25 '22 10:10

PiWi