0

I have constructed a horizontal bar chart as show with the code below. Everything looks great except what are supposed to be annotated bars. I can't figure out how to get the labels on the end of the bars and not in a table in the middle of the chart. Specifically, I'm looking at these lines of code:

for i, text in enumerate(ind):
    ax.annotate(str(x_axis), (ind[i], x_axis[i]),fontsize=14, color='black', va='center', ha='center')

Here's the whole thing:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
df0=pd.read_csv('sample1.csv')


fig, ax = plt.subplots(1, 1, figsize=(12,9))

ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

x_axis = 8.6667, 9.5, -8.4, 0, -4, 6
y_axis = Hospital
y_axis = 'A','B','C','D','E','F'
ind = np.arange(len(y_axis))

plt.xticks(fontsize=12)
plt.yticks(ind, y_axis, fontsize=14)
plt.tick_params(
axis='x',
which='both',
top='off')

plt.tick_params(
axis='y',
which='both',
right='off',
left='off')
plt.title('Super Awesome Title', fontsize=18, ha='center')

#Label Bars: First is the older, simpler way but it has issues...
#for a, b in zip(ind, y_axis):
#    plt.text(a, b, str(b), fontsize=16, color='black')
#Better, but more complex method:    
for i, text in enumerate(ind):
    ax.annotate(str(x_axis), (ind[i], x_axis[i]),fontsize=14, color='black', va='center', ha='center')

#Add padding around x_axis
plt.xlim([min(x_axis)-.5, max(x_axis)+.5])
#Add padding around y_axis
plt.ylim([min(ind)-.5, max(ind)+.5])

plt.barh(ind, x_axis, align='center', height=0.5, edgecolor='none', color='#AAA38E')
Dance Party2
  • 7,214
  • 17
  • 59
  • 106

1 Answers1

2

I just figured it out:

I had to switch ind and x_axis around and iterate over the x_axis:

   ax.annotate(str(x_axis), (ind[i], x_axis[i]) 

should be:

   ax.annotate(str(x_axis[i]), (x_axis[i], ind[i]) 
Dance Party2
  • 7,214
  • 17
  • 59
  • 106