Skip to content

Instantly share code, notes, and snippets.

@loganzartman
Last active March 5, 2018 01:21
Show Gist options
  • Save loganzartman/b3c9a99cb959ee523e013049afb604e6 to your computer and use it in GitHub Desktop.
Save loganzartman/b3c9a99cb959ee523e013049afb604e6 to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
def plot_bars(barGroups, barNames, groupNames, colors, ylabel="", title="", width=0.8):
"""Plot a grouped bar chart
barGroups - list of groups, where each group is a list of bar heights
barNames - list containing the name of each bar within any group
groupNames - list containing the name of each group
colors - list containing the color for each bar within a group
ylabel - label for the y-axis
title - title
"""
fig, ax = plt.subplots()
offset = lambda items, off: [x + off for x in items]
maxlen = max(len(group) for group in barGroups)
xvals = range(len(barGroups))
for i, bars in enumerate(zip(*barGroups)):
print(bars)
plt.bar(offset(xvals, i * width/maxlen), bars, width/maxlen, color=colors[i])
ax.set_ylabel(ylabel)
ax.set_title(title)
ax.set_xticks(offset(xvals, width / 2))
ax.set_xticklabels(groupNames)
# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
# Put a legend to the right of the current axis
ax.legend(barNames, loc="upper left", bbox_to_anchor=(1, 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment