我正在运行以下代码,以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_subplot(n_rows,n_cols,i+1)
df[var_name].hist(bins=10,ax=ax)
plt.title(var_name+"Distribution")
plt.show()
答案 0 :(得分:10)
您正在正确添加子图,但是您为每个添加的子图调用plt.show
,这会导致到目前为止绘制的内容被显示,即一个图。如果您在IPython中绘制内联图,则只能看到最后绘制的图。
Matplotlib提供了一些很好的examples如何使用子图。
您的问题修复如下:
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)
这给出了如下情节:
答案 1 :(得分:7)
如果你真的不担心标题,这里有一个单行
df = pd.DataFrame(np.random.randint(10, size=(100, 9)))
df.hist(color='k', alpha=0.5, bins=10)