Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Horizontal bar chart with autolabel
# a stacked bar plot with errorbars
%config InlineBackend.figure_format = 'retina'
import pandas as pd
from random import random
import matplotlib.pyplot as plt
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
width = rect.get_width()
ax.text(rect.get_x() + rect.get_width() / 2, rect.get_y() + rect.get_height()/2.,
'%.2f' % width,
ha='center', va='center', color='white')
def get_random():
a = random()
b = 1 - a - 0.25
c = 0.25
return {"a": a, "b": b, "c": c}
column_names = ['foo', 'bar', 'quz', 'quq']
df = pd.DataFrame([
get_random(),
get_random(),
get_random(),
get_random()
], index=column_names)
# Creates basic plot from data
ax = df.plot(kind='barh', stacked=True, legend=False)
# from now on, we'll control graph display with plt. commands
plt.title('Foobar', x=-.20, y=0.5, ha='right', va='center')
leg = plt.legend(bbox_to_anchor=[-0.20, 1])
autolabel(ax.patches)
ax.get_xaxis().set_visible(False)
#ax.get_xaxis().set_ticks([])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.