shobhit kumar
shobhit kumar

Reputation: 43

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?

Upvotes: 3

Views: 5742

Answers (2)

tmdavison
tmdavison

Reputation: 69116

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

Upvotes: 6

J-Eubanks
J-Eubanks

Reputation: 381

Use plt.barh() rather than using the vertical bar chart function.

Upvotes: 0

Related Questions