0

I was trying to plot a stacked bar chart from this data:

SYMBOL  COUNT    IMPACT
A  1       LOW
B  1       LOW
C  1       LOW
D  1       LOW
E  2       LOW
F  3       LOW
G  3       LOW
I  1       LOW
J  1  MODERATE
A  1  MODERATE
B  2  MODERATE
K  1  MODERATE
L  5  MODERATE
D  1  MODERATE
F  1  MODERATE
H  4  MODERATE
I  1  MODERATE
L  3      HIGH
E  1      HIGH
F  1      HIGH
G  1      HIGH

The idea is to make 3 bars (one per possible impact) and divide that bar into "SYMBOL". But I don't find the way of doing it without having to create manually a dictionary. Any help would be appreciated.

2

1 Answer 1

1

You'll need to pivot your data, but you can achieve a stacked bar plot like so:

Data manipulation:

plot_df = (df.pivot(index="SYMBOL", columns="IMPACT", values="COUNT")
           .fillna(0)
           .rename_axis(columns=None))

print(plot_df)

        HIGH  LOW  MODERATE
SYMBOL                     
A        0.0  1.0       1.0
B        0.0  1.0       2.0
C        0.0  1.0       0.0
D        0.0  1.0       1.0
E        1.0  2.0       0.0
F        1.0  3.0       1.0
G        1.0  3.0       0.0
H        0.0  0.0       4.0
I        0.0  1.0       1.0
J        0.0  0.0       1.0
K        0.0  0.0       1.0
L        3.0  0.0       5.0

Plotting:

from bokeh.plotting import figure
from bokeh.palettes import Category10_3
from bokeh.io import show

symbols = list(plot_df.index)
impacts = list(plot_df.columns)

source = ColumnDataSource(plot_df)

p = figure(width=500, height=250, x_range=symbols)
p.vbar_stack(impacts, width=0.7, x="SYMBOL", source=source, color=Category10_3, legend_label=impacts)

p.y_range.start = 0
p.xgrid.grid_line_color = None
p.legend.location = "top_left"

show(p)

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

You can change the ordering of the stacks by changing the value of impacts. So instead of impacts = list(plot_df.columns) you can do impacts = ["LOW", "MODERATE", "HIGH"] to ensure ordering low, moderate, high in your stacks.

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.