You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Matplotlib绘制圆形时出现AttributeError: 'module'无add_artist属性的问题

问题:Matplotlib添加半透明圆形时出现AttributeError错误

我想用Python在[0,1]区间随机生成的点集上方,绘制一个以(0.5, 0.5)为圆心的半透明圆形,编写了如下代码:

import numpy as np 
import matplotlib.pyplot as plt 

x_gal = np.random.rand(20) 
y_gal = np.random.rand(20) 
x_rand = np.random.rand(5*20) 
y_rand = np.random.rand(5*20) 

plt.figure(1) 
plt.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' ) 
plt.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' ) 
plt.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' ) 
plt.axis('off') 

circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5) 
plt.add_artist(circle1) 

plt.tight_layout() 
plt.show()

去掉与circle1相关的代码时能正常输出,但添加后出现如下错误:

AttributeError: 'module' object has no attribute 'add_artist'

请问我遗漏了什么?希望能得到帮助。


解决方案

哦,这个问题我之前也碰到过!问题出在plt.add_artist()这行代码上——plt是matplotlib的pyplot模块,而add_artist()方法其实是属于Axes对象(也就是我们绘图的坐标轴区域)的,并不是pyplot模块本身的方法,所以直接调用plt.add_artist()就会报错啦。

你可以用两种方式修改代码:

方式一:获取当前Axes对象

用plt.gca()(get current axes)获取当前正在使用的Axes对象,然后调用它的add_artist()方法:

import numpy as np 
import matplotlib.pyplot as plt 

x_gal = np.random.rand(20) 
y_gal = np.random.rand(20) 
x_rand = np.random.rand(5*20) 
y_rand = np.random.rand(5*20) 

plt.figure(1) 
plt.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' ) 
plt.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' ) 
plt.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' ) 
plt.axis('off') 

circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5) 
# 修改这里:获取当前Axes并调用add_artist
plt.gca().add_artist(circle1) 

plt.tight_layout() 
plt.show()

方式二:显式创建Figure和Axes对象(更推荐)

这种方式是matplotlib更规范的面向对象用法,直接创建Figure和Axes对象,所有绘图操作都基于Axes来完成:

import numpy as np 
import matplotlib.pyplot as plt 

x_gal = np.random.rand(20) 
y_gal = np.random.rand(20) 
x_rand = np.random.rand(5*20) 
y_rand = np.random.rand(5*20) 

# 显式创建figure和axes对象
fig, ax = plt.subplots(num=1) 
ax.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' ) 
ax.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' ) 
ax.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' ) 
ax.axis('off') 

circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5) 
ax.add_artist(circle1) 

plt.tight_layout() 
plt.show()

两种方式都能解决你的问题,第二种面向对象的写法更清晰,尤其是在处理多子图的时候会更方便哦。


内容的提问来源于stack exchange,提问作者Commoner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:53:51