代码报错的原因是在创建圆形 patch 时,使用了错误的参数名 circle_patch。应该使用 circle_patch = Circle((0, 0), radius=0.5, facecolor='red') 来创建圆形 patch。

正确的代码如下:

import matplotlib.pyplot as plt
from matplotlib.patches import Patch, Circle

# 创建圆形patch
circle_patch = Circle((0, 0), radius=0.5, facecolor='red')

# 创建图例元素
legend_elements = [Patch(color='#1A7D1A'), 
                   Patch(color='#9F67BF'),
                   Patch(color='#f29ca3'),
                   Patch(color='#2aa6de'),
                   Patch(color='#282727'),
                   circle_patch]

# 创建图例
plt.legend(handles=legend_elements, loc='upper right', labels=['2012','2016','2018','2019','other years'])

注意,创建圆形 patch 时,使用了 facecolor 参数来设置填充颜色。

Python Matplotlib 图例添加圆形:代码报错及解决方案

原文地址: https://www.cveoy.top/t/topic/pSrS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录