0
votes

I am trying to make a series of histograms by looping through a series of arrays containing values. For each array my script is producing a separate histogram. Using the default settings, this results in histograms in which the bar with the highest frequency touches the top of the graph (this is what it looks like now). I would like there to be some space: this is what I want it to look like.

My question is: how do I make the maximum value of the y-axis dependent of the maximum frequency occurring in my bins? I want the y-axis to be slightly longer than my longest bar.

I cannot do this by setting the value like so:

plt.axis([100, 350, 0, 5])  #[xmin, xmax, ymin, ymax]

or

matplotlib.pyplot.ylim(0,5) 

because I am plotting a series of histograms, and the max frequencies strongly vary.

My code now looks something like this:

import matplotlib.pyplot as plt

for LIST in LISTS:
    plt.figure()
    plt.hist(LIST)
    plt.title('Title')
    plt.xlabel("x-axis [unit]")
    plt.ylabel("Frequency")
    plt.savefig('figures/'LIST.png')

How do I define the y-axis to run from 0 to 1.1 * (the max frequency in 1 bin)?

1

1 Answers

0
votes

If I understand correctly, this is what you are hoping to achieve?

import matplotlib.pyplot as plt
import numpy.random as nprnd
import numpy as np

LISTS = []

#Generate data
for _ in range(3):
    LISTS.append(nprnd.randint(100, size=100))

#Find the maximum y value of every data set
maxYs = [i[0].max() for i in map(plt.hist,LISTS)]
print "maxYs:", maxYs

#Find the largest y 
maxY = np.max(maxYs)
print "maxY:",maxY

for LIST in LISTS:
    plt.figure()
    #Set that as the ylim
    plt.ylim(0,maxY)
    plt.hist(LIST)
    plt.title('Title')
    plt.xlabel("x-axis [unit]")
    plt.ylabel("Frequency")
    #Got rid of the safe function
plt.show()

Produces the graphs with the largest y limit the same as maxY. Also some debug output:

maxYs: [16.0, 13.0, 13.0]
maxY: 16.0

The function plt.hist() returns a tuple with the x, y data set. So you can call y.max() to get the maximum for each set. Source.