2

使用此代码绘制 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()

有什么建议为什么我会收到这个额外的情节以及如何删除它? 在此处输入图像描述

4

1 回答 1

1

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

因此,您的问题的答案是致电plt.subplots(1,1)。在评论中,您说您已尝试过,但出现错误。这是意料之中的。文档状态(强调我的):

回报:

图:matplotlib.figure.Figure 对象

ax :Axes 对象或 Axes 对象数组。

如果创建了多个子图,则ax 可以是单个 matplotlib.axes.Axes 对象或一组 Axes 对象。结果数组的尺寸可以用squeeze关键字控制,见上文。

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

df[df['Species'] == unv[i]].plot( (...) ,ax=ax, (...) )
于 2018-07-24T13:25:26.723 回答