Skip to content
Advertisement

How to add custom annotations, from the dataframe, to a stacked bar chart?

I’m plotting a cross-tabulation of various offices within certain categories. I’d like to put together a horizontal stacked bar chart where each office and its value is labeled.

Here’s some example code:

JavaScript

This gives me a fine starting point:

Stacked Bar Chart Example

However, what I’d like to have is this: Bar Chart with labels

After some research, I came up with the following code that correctly lines up labels on the ‘category’ axis:

JavaScript

But this doesn’t factor in the “stacking” of the bars. I’ve also tried iterating through the patches container returned by the plot command (which can let me retrieve x & y positions of each rectangle), but I then lose any connection to the office labels.

Advertisement

Answer

Figured it out. If I iterate through the columns of each row of the dataframe I can build up a list of the labels I need that matches the progression of the rectangles in ax.patches. Solution below:

JavaScript

Which, when added to the code above, yields:

Properly annotated bar chart

Now to just deal with re-arranging labels for bars that are too small.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement