0

I might be making a stupid mistake here, but I'm trying to get the 'xlim' values from a histogram that I've plotted.

data = np.random.normal(loc=10.0, scale=2.5, size=500)

plt.hist(data, bins=25, color='b')

x_min, x_max = plt.xlim()

print(x_min)
print(x_max)

Yet, when I compile the above lines, it returns to me 'x_min= 0' and 'x_max= 1.0' and a blank plot (Where the x axis ranges from 0 to 1)

Could someone tell me what's wrong?

DavidG
  • 24,279
  • 14
  • 89
  • 82
ricksanchez
  • 159
  • 1
  • 1
  • 7
  • 2
    I cannot reproduce this. Are you sure that is all the code you use to produce the problem? This might happen if you have accidentally create an empty figure by using `plt.figure()` _after_ `plt.hist()`? – DavidG Jul 16 '18 at 08:23
  • You seem to be using IPython or Juypter Notebook. Such information is utterly important and should not be left out from the question. – ImportanceOfBeingErnest Jul 16 '18 at 10:16
  • Sorry, I'll keep that in mind! – ricksanchez Jul 20 '18 at 02:46

1 Answers1

1

Use the same script or IPython cell

If you run the code from the question inside the same script of notebook cell, it will produce the desired output, namely print the limits of the histrogram.

enter image description here

If, however, you really want to run it from different cells, you would run into the problem of pyplot forgetting about its content in subsequent cells. In that case you have two options.

Use the object oriented approach

working on the objects, in this case the axes, directly via the respective methods (ax.get_xlim).

In[1]: fig, ax = plt.subplots()
       ax.hist(data, bins=25, color='b');

In[2]: x_min, x_max = ax.get_xlim()

In[3]: print(x_min)
       print(x_max)

enter image description here

Configure IPython not to close figures

You may use the IPython configuration to tell the backend not to close pyplot figures,

%config InlineBackend.close_figures=False # keep figures open in pyplot

In that case the code from the question would even work in different cells.

enter image description here

Similar question has also been asked here: How to overlay plots from different cells?

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712