surprisingly I didn’t find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:
import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.show()
import matplotlib.pyplot as plt
circle1 = plt.Circle((0,0),0.2, color='r')
circle2 = plt.Circle((0.5,0.5),0.2, color='blue')
circle3 = plt.Circle((1,1),0.2, color='g', clip_on=False)
fig, ax = plt.subplots()# note we must use plt.subplots, not plt.subplot# (or if you have an existing figure)# fig = plt.gcf()# ax = fig.gca()
ax.add_artist(circle1)
ax.add_artist(circle2)
ax.add_artist(circle3)
fig.savefig('plotcircles.png')
circle1 = plt.Circle((0,0),2, color='r')# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5,5),0.5, color='b', fill=False)
circle3 = plt.Circle((10,10),2, color='g', clip_on=False)
ax = plt.gca()
ax.cla()# clear things for fresh plot# change default range so that new circles will work
ax.set_xlim((0,10))
ax.set_ylim((0,10))# some data
ax.plot(range(11),'o', color='black')# key data point that we are encircling
ax.plot((5),(5),'o', color='y')
ax.add_artist(circle1)
ax.add_artist(circle2)
ax.add_artist(circle3)
fig.savefig('plotcircles2.png')
You need to add it to an axes. A Circle is a subclass of an Artist, and an axes has an add_artist method.
Here’s an example of doing this:
import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False)
fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()
ax.add_artist(circle1)
ax.add_artist(circle2)
ax.add_artist(circle3)
fig.savefig('plotcircles.png')
This results in the following figure:
The first circle is at the origin, but by default clip_on is True, so the circle is clipped when ever it extends beyond the axes. The third (green) circle shows what happens when you don’t clip the Artist. It extends beyond the axes (but not beyond the figure, ie the figure size is not automatically adjusted to plot all of your artists).
The units for x, y and radius correspond to data units by default. In this case, I didn’t plot anything on my axes (fig.gca() returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1.
Here’s a continuation of the example, showing how units matter:
circle1 = plt.Circle((0, 0), 2, color='r')
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False)
circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False)
ax = plt.gca()
ax.cla() # clear things for fresh plot
# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), 'o', color='black')
# key data point that we are encircling
ax.plot((5), (5), 'o', color='y')
ax.add_artist(circle1)
ax.add_artist(circle2)
ax.add_artist(circle3)
fig.savefig('plotcircles2.png')
which results in:
You can see how I set the fill of the 2nd circle to False, which is useful for encircling key results (like my yellow data point).
回答 1
import matplotlib.pyplot as plt
circle1=plt.Circle((0,0),.2,color='r')
plt.gcf().gca().add_artist(circle1)
import matplotlib.pyplot as plt
circle1=plt.Circle((0,0),.2,color='r')
plt.gcf().gca().add_artist(circle1)
A quick condensed version of the accepted answer, to quickly plug a circle into an existing plot. Refer to the accepted answer and other answers to understand the details.
from pylab import*
figure(figsize=(8,8))
ax=subplot(aspect='equal')#plot one circle (the biggest one on bottom-right)
circles(1,0,0.5,'r', alpha=0.2, lw=5, edgecolor='b', transform=ax.transAxes)#plot a set of circles (circles in diagonal)
a=arange(11)
out = circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none')
colorbar(out)
xlim(0,10)
ylim(0,10)
If you want to plot a set of circles, you might want to see this post or this gist(a bit newer). The post offered a function named circles.
The function circles works like scatter, but the sizes of plotted circles are in data unit.
Here’s an example:
from pylab import *
figure(figsize=(8,8))
ax=subplot(aspect='equal')
#plot one circle (the biggest one on bottom-right)
circles(1, 0, 0.5, 'r', alpha=0.2, lw=5, edgecolor='b', transform=ax.transAxes)
#plot a set of circles (circles in diagonal)
a=arange(11)
out = circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none')
colorbar(out)
xlim(0,10)
ylim(0,10)
回答 3
#!/usr/bin/pythonimport matplotlib.pyplot as plt
import numpy as np
def xy(r,phi):return r*np.cos(phi), r*np.sin(phi)
fig = plt.figure()
ax = fig.add_subplot(111,aspect='equal')
phis=np.arange(0,6.28,0.01)
r =1.
ax.plot(*xy(r,phis), c='r',ls='-')
plt.show()
import matplotlib.pyplot as plt
x =[1,2,3,4,5]
y =[10,20,30,40,50]
r =[100,80,60,40,20]# in points, not data units
fig, ax = plt.subplots(1,1)
ax.scatter(x, y, s=r)
fig.show()
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
r = [100, 80, 60, 40, 20] # in points, not data units
fig, ax = plt.subplots(1, 1)
ax.scatter(x, y, s=r)
fig.show()
回答 5
将常见问题扩展为可接受的答案。特别是:
以自然的长宽比查看圈子。
自动扩展轴限制以包括新绘制的圆。
独立的示例:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.add_patch(plt.Circle((0,0),0.2, color='r', alpha=0.5))
ax.add_patch(plt.Circle((1,1),0.5, color='#00ffff', alpha=0.5))
ax.add_artist(plt.Circle((1,0),0.5, color='#000033', alpha=0.5))#Use adjustable='box-forced' to make the plot area square-shaped as well.
ax.set_aspect('equal', adjustable='datalim')
ax.plot()#Causes an autoscale update.
plt.show()
Extending the accepted answer for a common usecase. In particular:
View the circles at a natural aspect ratio.
Automatically extend the axes limits to include the newly plotted circles.
Self-contained example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.add_patch(plt.Circle((0, 0), 0.2, color='r', alpha=0.5))
ax.add_patch(plt.Circle((1, 1), 0.5, color='#00ffff', alpha=0.5))
ax.add_artist(plt.Circle((1, 0), 0.5, color='#000033', alpha=0.5))
#Use adjustable='box-forced' to make the plot area square-shaped as well.
ax.set_aspect('equal', adjustable='datalim')
ax.plot() #Causes an autoscale update.
plt.show()
Note the difference between ax.add_patch(..) and ax.add_artist(..): of the two, only the former makes autoscaling machinery take the circle into account (reference: discussion), so after running the above code we get:
import matplotlib.pyplot as plt
import numpy as np
x = list(range(1,6))
y = list(range(10,20,2))print(x, y)for i, data in enumerate(zip(x,y)):
j, k = data
plt.scatter(j,k, marker ="o", s =((i+1)**4)*50, alpha =0.3)
centers = np.array([[5,18],[3,14],[7,6]])
m, n = make_blobs(n_samples=20, centers=[[5,18],[3,14],[7,6]], n_features=2,
cluster_std =0.4)
colors =['g','b','r','m']
plt.figure(num=None, figsize=(7,6), facecolor='w', edgecolor='k')
plt.scatter(m[:,0], m[:,1])for i in range(len(centers)):
plt.scatter(centers[i,0], centers[i,1], color = colors[i], marker ='o', s =13000, alpha =0.2)
plt.scatter(centers[i,0], centers[i,1], color ='k', marker ='x', s =50)
plt.savefig('plot.png')
I see plots with the use of (.circle) but based on what you might want to do you can also try this out:
import matplotlib.pyplot as plt
import numpy as np
x = list(range(1,6))
y = list(range(10, 20, 2))
print(x, y)
for i, data in enumerate(zip(x,y)):
j, k = data
plt.scatter(j,k, marker = "o", s = ((i+1)**4)*50, alpha = 0.3)
centers = np.array([[5,18], [3,14], [7,6]])
m, n = make_blobs(n_samples=20, centers=[[5,18], [3,14], [7,6]], n_features=2,
cluster_std = 0.4)
colors = ['g', 'b', 'r', 'm']
plt.figure(num=None, figsize=(7,6), facecolor='w', edgecolor='k')
plt.scatter(m[:,0], m[:,1])
for i in range(len(centers)):
plt.scatter(centers[i,0], centers[i,1], color = colors[i], marker = 'o', s = 13000, alpha = 0.2)
plt.scatter(centers[i,0], centers[i,1], color = 'k', marker = 'x', s = 50)
plt.savefig('plot.png')