Skip to main content
 首页 » 编程设计

python之带有 matplotlib 的额外空图

2024年12月31日11haluo1

使用此代码绘制 iris 数据集会给我一个额外的空图:

import pandas as pd 
from matplotlib import pyplot as plt 
 
d = {'Species': ['setosa', 'versicolor','virginica'], 'Sepal length': [1, 2, 3], 'Sepal width': [2, 4, 6]} 
 
df = pd.DataFrame(data=d) 
 
 
unv = df['Species'].unique() 
colorv = ['r','b','g'] 
markerv = ['v', 'o', '>'] 
 
 
#Getting an extra empty plot for no reason 
fig, ax=plt.subplots(1,2) 
for i in range(len(unv)): 
    df[df['Species'] == unv[i]].plot(x="Sepal length", y="Sepal width", kind="scatter",ax=ax[0],label=unv[i],color=colorv[i], marker = markerv[i]) 
 
plt.show() 

我为什么会收到这个额外的情节以及如何删除它有什么建议吗?

请您参考如下方法:

您将获得 2 个子图,因为您通过调用 plt.subplots(1,2) 请求两个子图,这会在 1 行和 2 列上创建 1*2 个子图。

因此,您问题的答案是调用 plt.subplots(1,1)。 在评论中,您说您已尝试但出现错误。这是意料之中的。 The documentation states (强调我的):

Returns:

fig : matplotlib.figure.Figure object

ax : Axes object or array of Axes objects.

ax can be either a single matplotlib.axes.Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

如果 subplots() 只返回一个轴,那么它会返回 Axes 对象而不是列表,因此您应该将调用修改为:

df[df['Species'] == unv[i]].plot( (...) ,ax=ax, (...) )