Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/plot/text.py
4034 views
1
"""
2
Text in plots
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 sage.plot.primitive import GraphicPrimitive
21
from sage.misc.decorators import options, rename_keyword
22
from sage.plot.colors import to_mpl_color
23
24
class Text(GraphicPrimitive):
25
"""
26
Base class for Text graphics primitive.
27
28
TESTS:
29
30
We test creating some text::
31
32
sage: text("I like Fibonacci",(3,5))
33
"""
34
def __init__(self, string, point, options):
35
"""
36
Initializes base class Text.
37
38
EXAMPLES::
39
40
sage: T = text("I like Fibonacci", (3,5))
41
sage: t = T[0]
42
sage: t.string
43
'I like Fibonacci'
44
sage: t.x
45
3.0
46
sage: t.options()['fontsize']
47
10
48
"""
49
self.string = string
50
self.x = float(point[0])
51
self.y = float(point[1])
52
GraphicPrimitive.__init__(self, options)
53
54
def get_minmax_data(self):
55
"""
56
Returns a dictionary with the bounding box data. Notice
57
that, for text, the box is just the location itself.
58
59
EXAMPLES::
60
61
sage: T = text("Where am I?",(1,1))
62
sage: t=T[0]
63
sage: t.get_minmax_data()['ymin']
64
1.0
65
sage: t.get_minmax_data()['ymax']
66
1.0
67
"""
68
from sage.plot.plot import minmax_data
69
return minmax_data([self.x], [self.y], dict=True)
70
71
def _repr_(self):
72
"""
73
String representation of Text primitive.
74
75
EXAMPLES::
76
77
sage: T = text("I like cool constants", (pi,e))
78
sage: t=T[0];t
79
Text 'I like cool constants' at the point (3.14159265359,2.71828182846)
80
"""
81
return "Text '%s' at the point (%s,%s)"%(self.string, self.x, self.y)
82
83
def _allowed_options(self):
84
"""
85
Return the allowed options for the Text class.
86
87
EXAMPLES::
88
89
sage: T = text("ABC",(1,1),zorder=3)
90
sage: T[0]._allowed_options()['fontsize']
91
'How big the text is.'
92
sage: T[0]._allowed_options()['zorder']
93
'The layer level in which to draw'
94
sage: T[0]._allowed_options()['rotation']
95
'how to rotate the text: angle in degrees, vertical, horizontal'
96
"""
97
return {'fontsize': 'How big the text is.',
98
'rgbcolor':'The color as an RGB tuple.',
99
'hue':'The color given as a hue.',
100
'axis_coords':'Uses axis coordinates -- (0,0) lower left and (1,1) upper right',
101
'rotation': 'how to rotate the text: angle in degrees, vertical, horizontal',
102
'vertical_alignment': 'how to align vertically: top, center, bottom',
103
'horizontal_alignment':'how to align horizontally: left, center, right',
104
'zorder':'The layer level in which to draw',
105
'clip': 'Whether to clip or not.'}
106
107
def _plot3d_options(self, options=None):
108
"""
109
Translate 2D plot options into 3D plot options.
110
111
EXAMPLES::
112
113
sage: T = text("ABC",(1,1))
114
sage: t = T[0]
115
sage: t.options()['rgbcolor']
116
(0.0, 0.0, 1.0)
117
sage: s=t.plot3d()
118
sage: s.jmol_repr(s.testing_render_params())[0][1]
119
'color atom [0,0,255]'
120
"""
121
if options == None:
122
options = dict(self.options())
123
options_3d = {}
124
# TODO: figure out how to implement rather than ignore
125
for s in ['axis_coords', 'clip', 'fontsize', 'horizontal_alignment',
126
'rotation', 'vertical_alignment' ]:
127
if s in options:
128
del options[s]
129
options_3d.update(GraphicPrimitive._plot3d_options(self, options))
130
return options_3d
131
132
def plot3d(self, **kwds):
133
"""
134
Plots 2D text in 3D.
135
136
EXAMPLES::
137
138
sage: T = text("ABC",(1,1))
139
sage: t = T[0]
140
sage: s=t.plot3d()
141
sage: s.jmol_repr(s.testing_render_params())[0][2]
142
'label "ABC"'
143
sage: s._trans
144
(1.0, 1.0, 0)
145
"""
146
from sage.plot.plot3d.shapes2 import text3d
147
options = self._plot3d_options()
148
options.update(kwds)
149
return text3d(self.string, (self.x, self.y, 0), **options)
150
151
def _render_on_subplot(self, subplot):
152
"""
153
TESTS::
154
155
sage: t1 = text("Hello",(1,1), vertical_alignment="top", fontsize=30, rgbcolor='black')
156
sage: t2 = text("World", (1,1), horizontal_alignment="left",fontsize=20, zorder=-1)
157
sage: t1 + t2 # render the sum
158
"""
159
options = self.options()
160
opts = {}
161
opts['color'] = options['rgbcolor']
162
opts['fontsize'] = int(options['fontsize'])
163
opts['verticalalignment'] = options['vertical_alignment']
164
opts['horizontalalignment'] = options['horizontal_alignment']
165
if 'zorder' in options:
166
opts['zorder'] = options['zorder']
167
if options['axis_coords']:
168
opts['transform'] = subplot.transAxes
169
if 'rotation' in options:
170
val = options['rotation']
171
if isinstance(val, str):
172
opts['rotation'] = options['rotation']
173
else:
174
opts['rotation'] = float(options['rotation'])
175
p=subplot.text(self.x, self.y, self.string, clip_on=options['clip'], **opts)
176
if not options['clip']:
177
self._bbox_extra_artists=[p]
178
179
180
@rename_keyword(color='rgbcolor')
181
@options(fontsize=10, rgbcolor=(0,0,1), horizontal_alignment='center',
182
vertical_alignment='center', axis_coords=False, clip=False)
183
def text(string, xy, **options):
184
r"""
185
Returns a 2D text graphics object at the point `(x,y)`.
186
187
Type ``text.options`` for a dictionary of options for 2D text.
188
189
2D OPTIONS:
190
191
- ``fontsize`` - How big the text is
192
193
- ``rgbcolor`` - The color as an RGB tuple
194
195
- ``hue`` - The color given as a hue
196
197
- ``rotation`` - How to rotate the text: angle in degrees, vertical, horizontal
198
199
- ``vertical_alignment`` - How to align vertically: top, center, bottom
200
201
- ``horizontal_alignment`` - How to align horizontally: left, center, right
202
203
- ``axis_coords`` - (default: False) if True, use axis coordinates, so that
204
(0,0) is the lower left and (1,1) upper right, regardless of the x and y
205
range of plotted values.
206
207
EXAMPLES::
208
209
sage: text("Sage is really neat!!",(2,12))
210
211
The same text in larger font and colored red::
212
213
sage: text("Sage is really neat!!",(2,12),fontsize=20,rgbcolor=(1,0,0))
214
215
Same text but guaranteed to be in the lower left no matter what::
216
217
sage: text("Sage is really neat!!",(0,0), axis_coords=True, horizontal_alignment='left')
218
219
Same text rotated around the left, bottom corner of the text::
220
221
sage: text("Sage is really neat!!",(0,0), rotation=45.0, horizontal_alignment='left', vertical_alignment='bottom')
222
223
Same text oriented vertically::
224
225
sage: text("Sage is really neat!!",(0,0), rotation="vertical")
226
227
You can also align text differently::
228
229
sage: t1 = text("Hello",(1,1), vertical_alignment="top")
230
sage: t2 = text("World", (1,0.5), horizontal_alignment="left")
231
sage: t1 + t2 # render the sum
232
233
You can save text as part of PDF output::
234
235
sage: text("sage", (0,0), rgbcolor=(0,0,0)).save(SAGE_TMP + 'a.pdf')
236
237
Text must be 2D (use the text3d command for 3D text)::
238
239
sage: t = text("hi",(1,2,3))
240
Traceback (most recent call last):
241
...
242
ValueError: use text3d instead for text in 3d
243
sage: t = text3d("hi",(1,2,3))
244
245
Extra options will get passed on to show(), as long as they are valid::
246
247
sage: text("MATH IS AWESOME", (0, 0), fontsize=40, axes=False)
248
sage: text("MATH IS AWESOME", (0, 0), fontsize=40).show(axes=False) # These are equivalent
249
"""
250
try:
251
x, y = xy
252
except ValueError:
253
if isinstance(xy, (list, tuple)) and len(xy) == 3:
254
raise ValueError, "use text3d instead for text in 3d"
255
raise
256
from sage.plot.all import Graphics
257
options['rgbcolor'] = to_mpl_color(options['rgbcolor'])
258
point = (float(x), float(y))
259
g = Graphics()
260
g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore='fontsize'))
261
g.add_primitive(Text(string, point, options))
262
return g
263
264