plot a groupby object with bokeh

泪湿孤枕 提交于 2020-08-03 10:21:51

问题


Consider the following MWE.

from pandas import DataFrame
from bokeh.plotting import figure
data = dict(x = [0,1,2,0,1,2],
            y = [0,1,2,4,5,6],
            g = [1,1,1,2,2,2])
df = DataFrame(data)
p = figure()
p.line( 'x', 'y', source=df[ df.g == 1 ] )
p.line( 'x', 'y', source=df[ df.g == 2 ] )

Ideally, I would like to compress the last to lines in one:

p.line( 'x', 'y', source=df.groupby('g') )

(Real life examples have a large and variable number of groups.) Is there any concise way to do this?


回答1:


I just found out that the following works

gby = df.groupby('g')
gby.apply( lambda d: p.line( 'x', 'y', source=d ) )

(it has some drawbacks, though).

Any better idea?




回答2:


I didn't come out with df.groupby so I used df.loc but maybe multi_line is what you are after:

from pandas import DataFrame
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource

data = dict(x = [0, 1, 2, 0, 1, 2],
            y = [0, 1, 2, 4, 5, 6],
            g = [1, 1, 1, 2, 2, 2])

df = DataFrame(data, index = data['g'])
dfs = [DataFrame(df.loc[i].values, columns = df.columns) for i in df['g'].unique()]
source = ColumnDataSource(dict(x = [df['x'].values  for df in dfs], y = [df['y'].values for df in dfs]))

p = figure()
p.multi_line('x', 'y', source = source)

show(p)

Result:




回答3:


This is Tony's solution slightly simplified.

import pandas as pd
from bokeh.plotting import figure
data = dict(x = [0, 1, 2, 0, 1, 2],
            y = [0, 1, 2, 4, 5, 6],
            g = [1, 1, 1, 2, 2, 2])
df = pd.DataFrame(data)
####################### So far as in the OP
gby = df.groupby('g')
p = figure()
x = [list( sdf['x'] ) for i,sdf in gby]
y = [list( sdf['y'] ) for i,sdf in gby]
p.multi_line( x, y )


来源:https://stackoverflow.com/questions/55592101/plot-a-groupby-object-with-bokeh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!