Using scatterplot()
使操作图例变得更容易。如果你使用legend='brief
然后你会得到这个图例:
您可以使用以下方法获取用于创建此图例的艺术家和标签:
h,l = ax.get_legend_handles_labels()
由于您只需要颜色信息,而不需要尺寸,因此解决方案只是使用艺术家的前半部分重新创建图例
ax.legend(h[:4],l[:4])
完整代码:
matplotlib.style.use('fivethirtyeight')
# load data
iris = sns.load_dataset('iris')
# plot
fig, ax = plt.subplots(figsize=(7,5))
sns.scatterplot(
'sepal_length',
'sepal_width',
hue='species',
size='petal_width',
alpha=0.75,
legend='brief',
data=iris,
ax=ax
)
# make adjustments
ax.set_xlabel('Sepal Length')
ax.set_ylabel('Sepal Width')
ax.text(x=0.5, y=1.1, s='Sepal Length vs Width', fontsize=16, weight='bold', ha='center', va='bottom', transform=ax.transAxes)
ax.text(x=0.5, y=1.05, s='The size of each point corresponds to sepal width', fontsize=8, alpha=0.75, ha='center', va='bottom', transform=ax.transAxes)
h,l = ax.get_legend_handles_labels()
ax.legend(h[:4],l[:4], bbox_to_anchor=(1.05, 1), loc=2)
fig.tight_layout()
plt.show()