为什么matplotlib在做子图时也要打印数据?

use*_*989 0 python matplotlib jupyter-notebook

嗨,我无法弄清楚如何正确地将pyplot用于多个绘图,除了绘图外,它还向我显示了完整的数据数组

# 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' 
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 5

您在问题中错过的重要信息是您正在使用Jupyter笔记本。为了在jupyter笔记本中显示绘图,您可以plt.show()在单元格的末尾调用,也可以使用%matplotlib inline后端。

如果使用多个子图,则最好使用oo接口,即不使用plt.hist(...)but axes[0,2].hist(...)。这样,您可以直接设置要绘制的轴。(plt.hist(..., ax=...)不存在-因此出错)

为了不打印数组,您可以ax.hist()通过在结尾(;)使用分号来禁止该行的输出。

axes[1,0].hist(x, 50);
Run Code Online (Sandbox Code Playgroud)

完整示例(使用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()
Run Code Online (Sandbox Code Playgroud)

完整示例(使用内联后端):

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); 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明