为什么matplotlib在进行子图时也会打印数据?

时间:2017-07-06 03:59:37

标签: 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' 

2 个答案:

答案 0 :(得分:4)

您在问题中遗漏的重要信息是您使用的是Jupyter笔记本。 为了在jupyter笔记本中显示情节,您可以在单元格的末尾调用plt.show(),或者您可以使用%matplotlib inline后端。

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

为了不打印数组,您可以在末尾使用分号(ax.hist())来抑制;行的输出。

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

完整示例(使用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()

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

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

答案 1 :(得分:1)

我无法在

中重现所描述的行为
axes[1,0].hist(x, 50)

即。直方图按预期绘制,不打印数组。在第二个语句中,ax不是有效的关键字。相反,您可以使用axes设置当前plt.sca()实例:

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

希望这有帮助。