Home > Software engineering >  How to draw histogram for array in python?
How to draw histogram for array in python?

Time:09-22

I have an array that has different values, some of which are duplicates. How can I draw a histogram for them whose horizontal axis is the name of the element and the vertical axis is the number in the array?

arr= ['a','a','a','b','c','b']

CodePudding user response:

You can use the matplotlib library to plot a histogram directly from a list. The code for it goes as follows:

from matplotlib import pyplot as plt

arr= ['a','a','a','b','c','b']

plt.hist(arr)
plt.show()

You can check out more about the histogram function from matplotlib out here:

It's certainly possible to fix this manually, but it's easier to use pandas or seaborn. Both use matplotlib under the hood, but they provide better default formatting.

Also:

  • If there are too many bars to fit comfortably in the default frame, you can widen the figsize. In these examples I've set figsize=(6, 3).
  • If you want to rotate the x ticks, add plt.xticks(rotation=90).

pandas

  • pandas


seaborn

  • seaborn

  • seaborn


matplotlib

  • numpy

  • Related