Skip to content

Instantly share code, notes, and snippets.

@benjaminmgross
Created June 1, 2014 08:12
Show Gist options
  • Save benjaminmgross/ca911e6cae8fef0d9ae8 to your computer and use it in GitHub Desktop.
Save benjaminmgross/ca911e6cae8fef0d9ae8 to your computer and use it in GitHub Desktop.
Exploding Bar Chart

#Why

I haven't seen any visualizations of "Exploding Bar Charts" using matplotlib like the this one:

exploding_bar

So I put together some very quick code to show how it could be done

#WIP

This is very much a WIP, right now the values of the expansion lines are hard coded, but I'm attempting to extract the Rectangle attributes to be choose which data point you are "exploding."

import pandas
import numpy
import matplotlib.pyplot as plt
def run_fun():
numpy.random.seed(seed = 69)
dat = pandas.DataFrame(numpy.random.randn(5, 2),
index = [letter for letter in 'abcde'],
columns = [0, 1])
color_a = ["#7F8392", "#B08B47", "#52A479", "#C6778A", "#CF7B5E"]
color_b = ["#829554", "#A78071", "#AD8AB2", "#679486", "#65A1BC"]
fig = plt.figure()
ax = plt.subplot2grid((1,1), (0,0))
stacked_barchart(ax, 0, dat.loc[:, 0], color_a)
stacked_barchart(ax, 1, dat.loc[:, 1], color_b)
ax.plot([.25, .75], [0., 2.2], color = '#353535', ls = '--')
ax.plot([.25, .75], [-1.6, -1.2], color = '#353535', ls = '--')
def stacked_barchart(ax, tick, series, colors):
neg_sum = series[series < 0].sum()
pos_sum = 0.
for i, val in enumerate(series):
if val < 0:
neg_sum -= val
ax.bar(tick, val, bottom = neg_sum, color = colors[i],
align = 'center', width = 0.5,
lw = .25, label = series.index[i])
else:
ax.bar(tick, val, bottom = pos_sum, align = 'center',
width = 0.5, color = colors[i],
label = series.index[i], lw = .25)
pos_sum += val
return ax

#Results

Running the code you should get an image that looks like this

exploding_bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment