I think its easier if you create two subplots and add the table to the left subplot, instead of deriving a new subplot from the single subplot you have now. If you add the table to an existing subplot, you can use the bbox
to stretch it from 0 to 1 (so fully) in the y-direction. Since the table has a header, setting the ylim
of the right plot to (0, n_items), will make both align properly, and adding a slight offset because the bars are also given an offset of 0.4 (offset of the outer bar + half a barwidth). This should work automatically if the number of elements changes.
bar_width = .2
fig, axs = plt.subplots(1,2, figsize=(12,6))
fig.subplots_adjust(wspace=0, top=1, right=1, left=0, bottom=0)
axs[1].barh(y_pos[::-1], num_tickets[::-1], bar_width, align='center', alpha=0.4, color='r')
axs[1].barh(y_pos_2[::-1], num_tickets_2[::-1], bar_width, align='center', alpha=0.4, color='b')
axs[1].barh(y_pos_3[::-1], num_tickets_3[::-1], bar_width, align='center', alpha=0.4, color='y')
axs[1].barh(y_pos_4[::-1], num_tickets_4[::-1], bar_width, align='center', alpha=0.4, color='g')
axs[1].set_yticks([])
axs[1].set_xlabel('Numbers')
axs[1].set_title('Horizontal Bar Chart with table')
axs[1].set_ylim(0 - .4, (len(appsol)) + .4)
cell_text = list(zip(num_tickets, num_tickets_2, num_tickets_3, num_tickets_4))
row_lables = appsol
column_labels = ['So Huge\nMice', 'Elephants', 'Reptiles', 'Germs']
axs[0].axis('off')
the_table = axs[0].table(cellText=cell_text,
rowLabels=row_lables,
colLabels=column_labels,
bbox=[0.4, 0.0, 0.6, 1.0])
the_table.set_fontsize(15)
plt.savefig('barh_graph.png')
plt.close('all')
If you look closely you might notice that the bars are ranging from the top of the table to the bottom, you could tweak them a bit to make them start at the center of the upper and lower cell of the table.