我是matplotlib的新手。我正在尝试将直方图绘制为散点图下方的子图。这是创建绘图的代码的一部分-CZs是Pandas DataFrame,而LinearRegression()是从sklearn.linear_model导入的:
X= CZs.loc[(CZs.index != '38300') & (CZs.index != '38100'), 'pop1960_puma60'].as_matrix()
X.shape = (CZs.shape[0]-2,1)
y= CZs.loc[(CZs.index != '38300') & (CZs.index != '38100'), 'pop1960'].as_matrix()
zs = CZs.loc[(CZs.index != '38300') & (CZs.index != '38100'), 'pop_diff'].as_matrix()
model = LinearRegression()
model = LinearRegression(fit_intercept = False).fit(X,y)
xs1 = np.linspace(0, 100000000, 2)
ys1= xs1*model.coef_
fig, axs = plt.subplots(2, 1, tight_layout=True)
plt.ylim( (0, 12000000) )
plt.xlim( (0, 12000000) )
axs[0].scatter(xs, ys, c = 'red')
axs[0].plot(xs1, ys1, c = 'blue')
axs[0].set(xlabel='Pop. from Weights', ylabel='Exact Population', title='Weight Check')
axs[0].ticklabel_format(useOffset=False, style='plain')
axs[1].hist(zs)
axs[1].set(xlabel='Relative Error', ylabel='Frequency')
plt.savefig("subplots.png", dpi = 600)
行
axs[1].hist(zs)
产生以下输出
/conda_env/lib/python3.7/site-packages/numpy/lib/histograms.py:824: RuntimeWarning: invalid value encountered in greater_equal keep = (tmp_a >= first_edge)
/conda_env/lib/python3.7/site-packages/numpy/lib/histograms.py:825: RuntimeWarning: invalid value encountered in less_equal
(array([ 1., 1., 4., 30., 638., 38., 3., 2., 2. 1.]),array([-0.03605981, -0.02805883, -0.02005785, -0.01205688, -0.0040559 , 0.00394507, 0.01194605, 0.01994702, 0.027948 , 0.03594898, 0.04394995]), <a list of 10 Patch objects>)
我不知道该怎么解释。
生成的数字如下(对不起,我不敢将图像放在行内):
错误图表,直方图为空
如您所见,直方图子图为空。
但是,如果我自己绘制直方图,问题就会消失。这段代码
zs = CZs.loc[(CZs.index != '38300') & (CZs.index != '38100'), 'pop_diff'].as_matrix()
fig, axs = plt.subplots(tight_layout=True)
axs.hist(zs)
axs.set(xlabel='Relative Error', ylabel='Frequency')
plt.savefig("hist.png", dpi = 600)
会产生相同的警告,但也会产生预期的直方图:
简单的直方图符合预期
这是怎么回事?如何修改代码,使其产生两个子图?