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()
... but still didn't get it working.
If you aim to have the "circle" maintain a visual aspect ratio of 1 no matter what the data coordinates are, you could use the scatter() method. http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.scatter
You need to add it to an axes. A
Circle
is a subclass of anArtist
, and anaxes
has anadd_artist
method.Here's an example of doing this:
This results in the following figure:
The first circle is at the origin, but by default
clip_on
isTrue
, so the circle is clipped when ever it extends beyond theaxes
. The third (green) circle shows what happens when you don't clip theArtist
. 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:
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).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.
By the way:
gcf()
means Get Current Figuregca()
means Get Current AxisOr, if you prefer, look at the
path
s, http://matplotlib.sourceforge.net/users/path_tutorial.htmlIf 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 likescatter
, but the sizes of plotted circles are in data unit.Here's an example:
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:
Note the difference between
ax.add_patch(..)
andax.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:See also:
set_aspect(..)
documentation.