Python 在网格中绘制多个直方图
我正在运行以下代码,以3×3的网格为9个变量绘制直方图。然而,它只绘制一个变量Python 在网格中绘制多个直方图,python,numpy,pandas,matplotlib,Python,Numpy,Pandas,Matplotlib,我正在运行以下代码,以3×3的网格为9个变量绘制直方图。然而,它只绘制一个变量 import pandas as pd import numpy as np import matplotlib.pyplot as plt def draw_histograms(df, variables, n_rows, n_cols): fig=plt.figure() for i, var_name in enumerate(variables): ax=fig.add_s
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def draw_histograms(df, variables, n_rows, n_cols):
fig=plt.figure()
for i, var_name in enumerate(variables):
ax=fig.add_subplot(n_rows,n_cols,i+1)
df[var_name].hist(bins=10,ax=ax)
plt.title(var_name+"Distribution")
plt.show()
您正在正确地添加子图,但您为每个添加的子图调用
plt.show
,从而显示到目前为止绘制的内容,即一个图。例如,如果在IPython中进行内联打印,则只能看到最后绘制的打印
Matplotlib提供了一些关于如何使用子图的好方法
您的问题已修复,如下所示:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def draw_histograms(df, variables, n_rows, n_cols):
fig=plt.figure()
for i, var_name in enumerate(variables):
ax=fig.add_subplot(n_rows,n_cols,i+1)
df[var_name].hist(bins=10,ax=ax)
ax.set_title(var_name+" Distribution")
fig.tight_layout() # Improves appearance a bit.
plt.show()
test = pd.DataFrame(np.random.randn(30, 9), columns=map(str, range(9)))
draw_histograms(test, test.columns, 3, 3)
它给出了一个类似于:
如果你真的不担心标题,这里有一句简单的话
df = pd.DataFrame(np.random.randint(10, size=(100, 9)))
df.hist(color='k', alpha=0.5, bins=10)