Matplotlib:未在子图中显示的直方图

2024-09-30 05:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我对matplotlib不熟悉。我试着在散点图下面画一个直方图作为子图。这是创建绘图的代码部分——CZs是一个数据帧,而LinearRegression()是从sklearn.linear\u模型地址:

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>)

我不知道怎么解释。你知道吗

产生的数字如下(对不起,我没有声誉把图像内联):

直方图为空的错误绘图 image

如您所见,直方图子图是空的。你知道吗

但是,如果我自己绘制直方图,问题就消失了。此代码

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)

生成相同的警告,但也生成预期的直方图:

简单的直方图 image

怎么回事?如何修改代码,使其生成两个子批?你知道吗


Tags: 代码indexmodellibasplt直方图matrix

热门问题