22

All the matplotlib examples with hist() generate a data set, provide the data set to the hist function with some bins (possibly non-uniformly spaced) and the function automatically calculates and then plots the histogram.

I already have histogram data and I simply want to plot it, how can I do that?! For example, I have the bins (half open ranges are denoted by the square and curved bracket notation),

[0, 1)   0
[1, 2)   3
[2, 3)   8
[3, 4)   6
[4, 5)   2
[5, 6)   3
[6, 7)   1
[7, 8)   0
Daniel Farrell
  • 9,316
  • 8
  • 39
  • 62

3 Answers3

22

Perhaps the weight parameter would be of help in your problem.

import matplotlib.pyplot as plt

a= [1,2,3,4,5,6,7,8,9]
b= [5,3,4,5,3,2,1,2,3]
plt.hist(a,9, weights=b)
plt.show()

Or, as tcaswell said, you could just make a bar plot and change the x-axis.

Using matplotlib how could I plot a histogram with given data in python

Is a link.

Community
  • 1
  • 1
3

Also, as an alternative (similar to Matlab), you can use bar:

import matplotlib.pyplot as plt

a= [1,2,3,4,5,6,7,8,9]
b= [5,3,4,5,3,2,1,2,3]
plt.bar(a,b)

enter image description here

Then, you can also add the title and other stuff and, finally, save the image:

plt.title("Clock cycles")
plt.grid()
plt.xlabel("Size of the matrices processed")
plt.ylabel("Clock cycles")
plt.savefig("clock_cycles.svg")
Leos313
  • 5,152
  • 6
  • 40
  • 69
  • With histogram your bars lie between the ticks, which makes more sense since the labels are actually ranges. With `.bar()` the bars are positioned on the ticks. – User 10482 Nov 14 '21 at 19:21
3

I'm surprised nobody mentioned plt.step here yet for making step plots...

a= [1,2,3,4,5,6,7,8,9]
b= [5,3,4,5,3,2,1,2,3]
plt.step(a,b)
Sven Geier
  • 81
  • 6