0

I have large data that I want to put into bins and display on a histogram. Yet, before I display the histogram, I want to make some arrangements on the data. The code is as follows:

import numpy as np
import matplotlib.pyplot as plt

data_set=np.random.randint(1000, size=1000)

c = 5
a, b = np.histogram(data_set, bins=20) 
a = [i * c for i in a]             

fig, ax = plt.subplots(figsize=(8, 5))
ax.hist(a, bins=b, alpha=0.8) 
plt.show()

I can manage plotting using plt.hist(data_set, bins=20), but I can't do it after I play with the histogram data. In this case, I multiplied all the entries by 5, but the manipulation can be more complicated.

How do I plot a histogram using np.histogram() output?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
ck1987pd
  • 267
  • 2
  • 11
  • 1
    Why `a=[i*c for i in a]` instead of `a *= c`? – Mad Physicist Sep 25 '20 at 18:46
  • @MadPhysicist Honestly, I don't know it works that way. When I do ```a=a*c```, it makes c copies of a and concatenate them, as if I am operating on strings. – ck1987pd Sep 25 '20 at 18:48
  • That's because you turned `a` into a list for some reason. Rerun the script, with the one line replaced. – Mad Physicist Sep 25 '20 at 18:48
  • @MadPhysicist But mine works for both arrays and lists. Isn't it better? Some functions output lists for some reason, and it is hard to keep track of them. – ck1987pd Sep 25 '20 at 18:50
  • Except for `np.split`, I can't think of a numpy function that outputs lists. `np.histogram` certainly doesn't. There is no advantage to using lists with numpy or matplotlib. You just make things go slower as you convert back and forth. Also, try timing your method vs mine for 10^6 elements. – Mad Physicist Sep 25 '20 at 18:51
  • @MadPhysicist I think I found the problem. ```map()``` gives lists instead of arrays, I guess. I will include use ```np.asarray(map())``` to keep everything as array. Then I can use your suggestion. – ck1987pd Sep 28 '20 at 10:40
  • @MadPhysicist I haven't asked about arrays or maps, you commented on something I didn't ask and I just told you why I used ```a=[i*c for i in a]```. The question is already closed for being duplicate and I got my answer. I don't know why you downvote it. – ck1987pd Sep 28 '20 at 12:17
  • @MadPhysicist It doesn't make much sense for me to delete the question, it might be a signpost for other people to get to the duplicate question. Mods can delete it if they think it is not worthy of being a signpost. – ck1987pd Sep 28 '20 at 12:20
  • 1
    Fair point. I'd completely forgotten what the question was about and didn't read. My mistake. – Mad Physicist Sep 28 '20 at 12:42

0 Answers0