Alp*_*lph 2 python numpy matplotlib pandas
我运行以下代码以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()
Run Code Online (Sandbox Code Playgroud)
Ric*_*ren 11
您正在添加正确的子图,但是您需要调用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)
Run Code Online (Sandbox Code Playgroud)
这给出了如下情节:

如果你真的不担心标题,这里是一个单行
df = pd.DataFrame(np.random.randint(10, size=(100, 9)))
df.hist(color='k', alpha=0.5, bins=10)
Run Code Online (Sandbox Code Playgroud)
