user1946989
user1946989

Reputation: 387

Why matplotlib is also printing data while doing a subplot?

Hi I can t figure out how to properly use pyplot for multiple plots, in addition to the plot it also print me the full array of data

# import numpy as np
import matplotlib.mlab as mlab 
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50) # kinda work, the problem is it print the array and then do the plot

plt.hist(x, 50, ax=axes[0,0]) # not wokring inner() got multiple values for keyword argument 'ax' 

Upvotes: 1

Views: 1597

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339590

The important information you missed in the question is that you are using a Jupyter Notebook. In order to show a plot in a jupyter notebook you may call plt.show() at the end of the cell, or you may use %matplotlib inline backend.

If using several subplots it's best to use the oo interface, i.e. not using plt.hist(...) but axes[0,2].hist(...). This way you directly set the axes to which to plot. (plt.hist(..., ax=...) does not exist - hence the error)

In order not to have the array printed you may suppress the output from the ax.hist() line by using a semicolon at the end (;).

axes[1,0].hist(x, 50);

Complete Example (using plt.show()):

import numpy as np
import matplotlib.mlab as mlab 
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50); 
axes[3,1].hist(x, 50);

plt.show()

Complete example (using inline backend):

import numpy as np
import matplotlib.mlab as mlab 
import matplotlib.pyplot as plt
%matplotlib inline

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50); 
axes[3,1].hist(x, 50); 

enter image description here

Upvotes: 5

Thomas Kühn
Thomas Kühn

Reputation: 9820

I cannot reproduce the described behaviour in

axes[1,0].hist(x, 50)

i.e. the histogram is plotted as expected and the array is not printed. In the second statement, ax is not a valid keyword. Instead you can set the current axes instance with plt.sca():

plt.sca(axes[0,0])
plt.hist(x, 50)

Hope this helps.

Upvotes: 1

Related Questions