优化这段代码col1=[ 'policy_state', 'insured_sex', 'insured_education_level', 'insured_relationship', 'incident_type', 'authorities_contacted', \ 'incident_state', 'auto_make'] plt.figure(figsize=(20,10)) j=1 for col in col1: ax=plt.subplot(4,4,j) ax=plt.scatter(x=range(len(df)),y=df[col],color='red') plt.title(col) j+=1 k=9 for col in col1: ax=plt.subplot(4,4,k) ax=plt.scatter(x=range(len(test)),y=test[col],color='cyan') plt.title(col) k+=1 plt.subplots_adjust(wspace=0.4,hspace=0.3) # 调整图间距 plt.show()
时间: 2023-12-09 10:05:58 浏览: 203
可以考虑将两个 for 循环合并为一个,减少重复代码。另外,可以使用 enumerate() 函数来遍历 col1 列表,并在循环中直接获取索引和元素值,避免使用计数器 j 和 k。最终代码如下:
```
col1 = ['policy_state', 'insured_sex', 'insured_education_level', 'insured_relationship', 'incident_type', 'authorities_contacted', 'incident_state', 'auto_make']
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(20, 10))
axes = axes.flatten()
for i, col in enumerate(col1):
axes[i].scatter(x=range(len(df)), y=df[col], color='red')
axes[i].set_title(col)
axes[i+8].scatter(x=range(len(test)), y=test[col], color='cyan')
axes[i+8].set_title(col)
plt.subplots_adjust(wspace=0.4, hspace=0.3)
plt.show()
```
这个版本的代码使用了 subplots() 函数创建一个包含多个子图的图形对象,然后使用 flatten() 函数将子图展开为一维数组,便于使用 enumerate() 函数遍历。在循环中,直接通过索引获取到对应的子图对象,然后调用 scatter() 函数来绘制散点图,并设置子图标题。最后,调用 subplots_adjust() 函数调整子图之间的间距,并使用 show() 函数显示图形。
阅读全文
相关推荐


















