Putting names inside bars in a bar plot in python

Viewed 1102

I have two lists, one of them is names, the other one is values. I want y axis to be values, x axis to be names. But names are too long to be put on axis, that's why I want to put them into bars, like on the picture, but bars should be vertical. enter image description here

On the picture, my namelist represent names of cities.

My input is as such:

mylist=[289.657,461.509,456.257]
nameslist=['Bacillus subtilis','Caenorhabditis elegans','Arabidopsis thaliana']

my code:

fig = plt.figure()
width = 0.35
ax = fig.add_axes([1,1,1,1])
ax.bar(nameslist,mylist,width)
ax.set_ylabel('Average protein length')
ax.set_xlabel('Names')
ax.set_title('Average protein length by bacteria')  

Any help appreciated!

1 Answers

ax.text can be used to place text at a given x and y position. To fit into a vertical bar, the text should be rotated 90 degrees. The text could either start at the top, or have its anchor point at the bottom. The alignment should be respectively top or bottom. A fontsize can be chosen to fit well to the image. The text color should be sufficiently contrasting to the color of the bars. An additional space can be used to have some padding.

Alternatively, there is ax.annotate with more options for positioning and decorating.

from matplotlib import pyplot as plt
import numpy as np

mylist = [289.657, 461.509, 456.257]
nameslist = ['Bacillus subtilis', 'Caenorhabditis elegans', 'Arabidopsis thaliana']

fig, ax = plt.subplots()
width = 0.35
ax.bar(nameslist, mylist, width, color='darkorchid')
for i, (name, height) in enumerate(zip(nameslist, mylist)):
    ax.text(i, height, ' ' + name, color='seashell',
            ha='center', va='top', rotation=-90, fontsize=18)
ax.set_ylabel('Average protein length')
ax.set_title('Average protein length by bacteria')
ax.set_xticks([]) # remove the xticks, as the labels are now inside the bars

plt.show()

resulting plot

Related