Commoner
Commoner

Reputation: 1768

Error while plotting circles using matplotlib

I want to draw a (semi-transparent) circle on top of an array of randomly generated points (between [0,1] ) using python. I want the circle to be centered at (0.5, 0.5)

This is the code that I have written:

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()

Without the lines in the code which refer to circle1, I get normal output (without the desired circle). But when I include the lines in the code which refer to circle1, I get the following error output.

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

What am I missing here? Any help will be greatly appreciated.

Upvotes: 1

Views: 449

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

You need to use add_artist from axes, the following is the quickest way to get the current axes using plt.gcf, get current figure, and get_gca, get current axes, also I recommend plt.axis('equal') to draw a circle vs oval:

import numpy as np
import matplotlib.pyplot as plt 
import matplotlib as mpl

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')
plt.axis('equal')

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

plt.tight_layout()
plt.show()

enter image description here

Upvotes: 1

harpan
harpan

Reputation: 8631

You need to plot on axis.

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()

Output:

enter image description here

Upvotes: 1

Related Questions