akasolace akasolace - 8 months ago 97
Python Question

Bar chart pandas Dataframe with Bokeh

I have the following df:

[A B C D
1Q18 6.9 0.0 25.0 9.9
2Q17 NaN NaN NaN NaN
2Q18 7.1 0.0 25.0 4.1
3Q17 NaN NaN NaN NaN
3Q18 7.3 0.0 25.0 5.3
4Q17 NaN NaN NaN NaN
4Q18 7.0 0.0 25.0 8.3]


And I would like to obtain a graph such as the one below

I tried first with Bar(df) but it only graph the first column

p=Bar(df)
show(p)


I also tried:

p=Bar(popo, values=["A","B"])
show(p)
>raise ValueError("expected an element of either %s, got %r" % (nice_join(self.type_params), value))
ValueError: expected an element of either Column(Float) or Column(String), got array([[ 6.9, 0. ]])


thank you in advance for letting me what I am doing wrong

cheers

Answer Source

You need first dataframe reshape by stack and then use parameter group:

from bokeh.charts import Bar, output_file, show

df = df.stack(dropna=False).rename_axis(['a','b']).reset_index(name='c')
print (df)
       a  b     c
0   1Q18  A   6.9
1   1Q18  B   0.0
2   1Q18  C  25.0
3   1Q18  D   9.9
4   2Q17  A   NaN
5   2Q17  B   NaN
6   2Q17  C   NaN
7   2Q17  D   NaN
8   2Q18  A   7.1
9   2Q18  B   0.0
10  2Q18  C  25.0
11  2Q18  D   4.1
12  3Q17  A   NaN
13  3Q17  B   NaN
14  3Q17  C   NaN
15  3Q17  D   NaN
16  3Q18  A   7.3
17  3Q18  B   0.0
18  3Q18  C  25.0
19  3Q18  D   5.3
20  4Q17  A   NaN
21  4Q17  B   NaN
22  4Q17  C   NaN
23  4Q17  D   NaN
24  4Q18  A   7.0
25  4Q18  B   0.0
26  4Q18  C  25.0
27  4Q18  D   8.3

p=Bar(df, 'a', values='c', group='b')
output_file("bar.html")
show(p)

graph

Also if need remove NaN values omit parameter dropna=False in stack:

df = df.stack().rename_axis(['a','b']).reset_index(name='c')
print (df)
       a  b     c
0   1Q18  A   6.9
1   1Q18  B   0.0
2   1Q18  C  25.0
3   1Q18  D   9.9
4   2Q18  A   7.1
5   2Q18  B   0.0
6   2Q18  C  25.0
7   2Q18  D   4.1
8   3Q18  A   7.3
9   3Q18  B   0.0
10  3Q18  C  25.0
11  3Q18  D   5.3
12  4Q18  A   7.0
13  4Q18  B   0.0
14  4Q18  C  25.0
15  4Q18  D   8.3

p=Bar(df, 'a', values='c', group='b')
output_file("bar.html")
show(p)

graph1