Why matplotlib is also printing data while doing a subplot?

安稳与你 提交于 2019-12-12 10:29:14

问题


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' 

回答1:


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); 




回答2:


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.



来源:https://stackoverflow.com/questions/44939577/why-matplotlib-is-also-printing-data-while-doing-a-subplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!