使用matplotlib绘制圆圈时出错

时间:2018-05-23 18:39:20

标签: python python-2.7 matplotlib

我想使用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的行,我会得到正常输出(没有所需的圆圈)。但是当我在代码中包含引用circle1的行时,我得到以下错误输出。

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

我在这里缺少什么?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您需要在轴上绘图。

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)

fig = plt.figure(1)
ax = fig.add_subplot(111)
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()

输出:

enter image description here

答案 1 :(得分:1)

你需要从轴使用add_artist,以下是使用plt.gcf获取当前轴的最快方法,获取当前数字,get_gca获取当前轴,我还建议{{1绘制圆形与椭圆形:

plt.axis('equal')

enter image description here

相关问题