Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot Horizontal bar graph from a dictionary using matplotlib?

I am using:

plt.bar(range(len(d)), d.values(), align='center')
plt.yticks(range(len(d)), d.keys())
plt.xlabel('frequency', fontsize=18)
plt.ylabel('keywords', fontsize=18)

plt.show()

and I am getting the output below: enter image description here

but I want to show the corresponding bar for each keyword on the y-axis, rather than the x-axis. How can I achieve that?

like image 793
shobhit kumar Avatar asked Mar 17 '26 06:03

shobhit kumar


1 Answers

Using matplotlib's barh() function will create a horizontal bar chart for you:

plt.barh(range(len(d)), d.values(), align='center')

From the docs:

matplotlib.pyplot.barh(bottom, width, height=0.8, left=None, hold=None, **kwargs)

Make a horizontal bar plot with rectangles bounded by:

left, left + width, bottom, bottom + height

(left, right, bottom and top edges)

bottom, width, height, and left can be either scalars or sequences

Also see the barh demo on the matplotlib gallery page here

like image 54
tmdavison Avatar answered Mar 18 '26 18:03

tmdavison