Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/plot/circle.py
4034 views
1
"""
2
Circles
3
"""
4
#*****************************************************************************
5
# Copyright (C) 2006 Alex Clemesha <[email protected]>,
6
# William Stein <[email protected]>,
7
# 2008 Mike Hansen <[email protected]>,
8
#
9
# Distributed under the terms of the GNU General Public License (GPL)
10
#
11
# This code is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
# General Public License for more details.
15
#
16
# The full text of the GPL is available at:
17
#
18
# http://www.gnu.org/licenses/
19
#*****************************************************************************
20
from primitive import GraphicPrimitive
21
from sage.misc.decorators import options, rename_keyword
22
from sage.plot.colors import to_mpl_color
23
from math import sin, cos, pi
24
25
class Circle(GraphicPrimitive):
26
"""
27
Primitive class for the Circle graphics type. See circle? for information
28
about actually plotting circles.
29
30
INPUT:
31
32
- x - `x`-coordinate of center of Circle
33
34
- y - `y`-coordinate of center of Circle
35
36
- r - radius of Circle object
37
38
- options - dict of valid plot options to pass to constructor
39
40
EXAMPLES:
41
42
Note this should normally be used indirectly via ``circle``::
43
44
sage: from sage.plot.circle import Circle
45
sage: C = Circle(2,3,5,{'zorder':2})
46
sage: C
47
Circle defined by (2.0,3.0) with r=5.0
48
sage: C.options()['zorder']
49
2
50
sage: C.r
51
5.0
52
53
TESTS:
54
55
We test creating a circle::
56
57
sage: C = circle((2,3), 5)
58
"""
59
def __init__(self, x, y, r, options):
60
"""
61
Initializes base class Circle.
62
63
EXAMPLES::
64
65
sage: C = circle((2,3), 5, edgecolor='red', alpha=.5, fill=True)
66
sage: C[0].x
67
2.0
68
sage: C[0].r
69
5.0
70
sage: C[0].options()['edgecolor']
71
'red'
72
sage: C[0].options()['alpha']
73
0.500000000000000
74
"""
75
self.x = float(x)
76
self.y = float(y)
77
self.r = float(r)
78
GraphicPrimitive.__init__(self, options)
79
80
def get_minmax_data(self):
81
"""
82
Returns a dictionary with the bounding box data.
83
84
EXAMPLES::
85
86
sage: p = circle((3, 3), 1)
87
sage: d = p.get_minmax_data()
88
sage: d['xmin']
89
2.0
90
sage: d['ymin']
91
2.0
92
"""
93
from sage.plot.plot import minmax_data
94
return minmax_data([self.x - self.r, self.x + self.r],
95
[self.y - self.r, self.y + self.r],
96
dict=True)
97
98
def _allowed_options(self):
99
"""
100
Return the allowed options for the Circle class.
101
102
EXAMPLES::
103
104
sage: p = circle((3, 3), 1)
105
sage: p[0]._allowed_options()['alpha']
106
'How transparent the figure is.'
107
sage: p[0]._allowed_options()['facecolor']
108
'2D only: The color of the face as an RGB tuple.'
109
"""
110
return {'alpha':'How transparent the figure is.',
111
'fill':'Whether or not to fill the circle.',
112
'legend_label':'The label for this item in the legend.',
113
'thickness':'How thick the border of the circle is.',
114
'edgecolor':'2D only: The color of the edge as an RGB tuple.',
115
'facecolor':'2D only: The color of the face as an RGB tuple.',
116
'rgbcolor':'The color (edge and face) as an RGB tuple.',
117
'hue':'The color given as a hue.',
118
'zorder':'2D only: The layer level in which to draw',
119
'linestyle':"2D only: The style of the line, which is one of 'dashed', 'dotted', 'solid', 'dashdot'.",
120
'clip': 'Whether or not to clip the circle.'}
121
122
def _repr_(self):
123
"""
124
String representation of Circle primitive.
125
126
EXAMPLES::
127
128
sage: C = circle((2,3), 5)
129
sage: c = C[0]; c
130
Circle defined by (2.0,3.0) with r=5.0
131
"""
132
return "Circle defined by (%s,%s) with r=%s"%(self.x, self.y, self.r)
133
134
def _render_on_subplot(self, subplot):
135
"""
136
TESTS::
137
138
sage: C = circle((2,pi), 2, edgecolor='black', facecolor='green', fill=True)
139
"""
140
import matplotlib.patches as patches
141
options = self.options()
142
p = patches.Circle((float(self.x), float(self.y)), float(self.r), clip_on=options['clip'])
143
if not options['clip']:
144
self._bbox_extra_artists=[p]
145
p.set_linewidth(float(options['thickness']))
146
p.set_fill(options['fill'])
147
a = float(options['alpha'])
148
p.set_alpha(a)
149
ec = to_mpl_color(options['edgecolor'])
150
fc = to_mpl_color(options['facecolor'])
151
if 'rgbcolor' in options:
152
ec = fc = to_mpl_color(options['rgbcolor'])
153
p.set_edgecolor(ec)
154
p.set_facecolor(fc)
155
p.set_linestyle(options['linestyle'])
156
p.set_label(options['legend_label'])
157
z = int(options.pop('zorder', 0))
158
p.set_zorder(z)
159
subplot.add_patch(p)
160
161
def plot3d(self, z=0, **kwds):
162
"""
163
Plots a 2D circle (actually a 50-gon) in 3D,
164
with default height zero.
165
166
INPUT:
167
168
169
- ``z`` - optional 3D height above `xy`-plane.
170
171
EXAMPLES:
172
173
sage: circle((0,0), 1).plot3d()
174
175
This example uses this method implicitly, but does not pass
176
the optional parameter z to this method::
177
178
sage: sum([circle((random(),random()), random()).plot3d(z=random()) for _ in range(20)])
179
180
These examples are explicit, and pass z to this method::
181
182
sage: C = circle((2,pi), 2, hue=.8, alpha=.3, fill=True)
183
sage: c = C[0]
184
sage: d = c.plot3d(z=2)
185
sage: d.texture.opacity
186
0.300000000000000
187
188
::
189
190
sage: C = circle((2,pi), 2, hue=.8, alpha=.3, linestyle='dotted')
191
sage: c = C[0]
192
sage: d = c.plot3d(z=2)
193
sage: d.jmol_repr(d.testing_render_params())[0][-1]
194
'color $line_1 translucent 0.7 [204,0,255]'
195
"""
196
options = dict(self.options())
197
fill = options['fill']
198
for s in ['clip', 'edgecolor', 'facecolor', 'fill', 'linestyle',
199
'zorder']:
200
if s in options:
201
del options[s]
202
203
n = 50
204
dt = float(2*pi/n)
205
x, y, r = self.x, self.y, self.r
206
xdata = [x+r*cos(t*dt) for t in range(n+1)]
207
ydata = [y+r*sin(t*dt) for t in range(n+1)]
208
if fill:
209
from polygon import Polygon
210
return Polygon(xdata, ydata, options).plot3d(z)
211
else:
212
from line import Line
213
return Line(xdata, ydata, options).plot3d().translate((0,0,z))
214
215
@rename_keyword(color='rgbcolor')
216
@options(alpha=1, fill=False, thickness=1, edgecolor='blue', facecolor='blue', linestyle='solid',
217
zorder=5, legend_label=None, clip=True, aspect_ratio=1.0)
218
def circle(center, radius, **options):
219
"""
220
Return a circle at a point center = `(x,y)` (or `(x,y,z)` and
221
parallel to the `xy`-plane) with radius = `r`. Type
222
``circle.options`` to see all options.
223
224
OPTIONS:
225
226
- ``alpha`` - default: 1
227
228
- ``fill`` - default: False
229
230
- ``thickness`` - default: 1
231
232
- ``linestyle`` - default: 'solid' (2D plotting only)
233
234
- ``edgecolor`` - default: 'blue' (2D plotting only)
235
236
- ``facecolor`` - default: 'blue' (2D plotting only, useful only
237
if ``fill=True``)
238
239
- ``rgbcolor`` - 2D or 3D plotting. This option overrides
240
``edgecolor`` and ``facecolor`` for 2D plotting.
241
242
- ``legend_label`` - the label for this item in the legend
243
244
EXAMPLES:
245
246
The default color is blue, but this is easy to change::
247
248
sage: c = circle((1,1), 1)
249
sage: c
250
251
::
252
253
sage: c = circle((1,1), 1, rgbcolor=(1,0,0))
254
sage: c
255
256
We can also use this command to plot three-dimensional circles parallel
257
to the `xy`-plane::
258
259
sage: c = circle((1,1,3), 1, rgbcolor=(1,0,0))
260
sage: c
261
sage: type(c)
262
<class 'sage.plot.plot3d.base.TransformGroup'>
263
264
To correct the aspect ratio of certain graphics, it is necessary
265
to show with a ``figsize`` of square dimensions::
266
267
sage: c.show(figsize=[5,5],xmin=-1,xmax=3,ymin=-1,ymax=3)
268
269
Here we make a more complicated plot, with many circles of different colors::
270
271
sage: g = Graphics()
272
sage: step=6; ocur=1/5; paths=16;
273
sage: PI = math.pi # numerical for speed -- fine for graphics
274
sage: for r in range(1,paths+1):
275
... for x,y in [((r+ocur)*math.cos(n), (r+ocur)*math.sin(n)) for n in srange(0, 2*PI+PI/step, PI/step)]:
276
... g += circle((x,y), ocur, rgbcolor=hue(r/paths))
277
... rnext = (r+1)^2
278
... ocur = (rnext-r)-ocur
279
...
280
sage: g.show(xmin=-(paths+1)^2, xmax=(paths+1)^2, ymin=-(paths+1)^2, ymax=(paths+1)^2, figsize=[6,6])
281
282
Note that the ``rgbcolor`` option overrides the other coloring options.
283
This produces red fill in a blue circle::
284
285
sage: circle((2,3), 1, fill=True, edgecolor='blue')
286
287
This produces an all-green filled circle::
288
289
sage: circle((2,3), 1, fill=True, edgecolor='blue', rgbcolor='green')
290
291
The option ``hue`` overrides *all* other options, so be careful with its use.
292
This produces a purplish filled circle::
293
294
sage: circle((2,3), 1, fill=True, edgecolor='blue', rgbcolor='green', hue=.8)
295
296
And a circle with a legend::
297
298
sage: circle((4,5), 1, rgbcolor='yellow', fill=True, legend_label='the sun').show(xmin=0, ymin=0)
299
300
Extra options will get passed on to show(), as long as they are valid::
301
302
sage: circle((0, 0), 2, figsize=[10,10]) # That circle is huge!
303
304
::
305
306
sage: circle((0, 0), 2).show(figsize=[10,10]) # These are equivalent
307
308
TESTS:
309
310
We cannot currently plot circles in more than three dimensions::
311
312
sage: circle((1,1,1,1), 1, rgbcolor=(1,0,0))
313
Traceback (most recent call last):
314
...
315
ValueError: The center of a plotted circle should have two or three coordinates.
316
317
The default aspect ratio for a circle is 1.0::
318
319
sage: P = circle((1,1), 1)
320
sage: P.aspect_ratio()
321
1.0
322
"""
323
from sage.plot.all import Graphics
324
g = Graphics()
325
g._set_extra_kwds(Graphics._extract_kwds_for_show(options))
326
g.add_primitive(Circle(center[0], center[1], radius, options))
327
if options['legend_label']:
328
g.legend(True)
329
if len(center)==2:
330
return g
331
elif len(center)==3:
332
return g[0].plot3d(z=center[2])
333
else:
334
raise ValueError, 'The center of a plotted circle should have two or three coordinates.'
335
336