This repository was archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgraphics.py
3532 lines (2760 loc) · 131 KB
/
graphics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
r"""
Graphics objects
This file contains the definition of the class :class:`Graphics`.
Usually, you don't call the constructor of this class directly
(although you can do it), you would use :func:`plot` instead.
AUTHORS:
- Jeroen Demeyer (2012-04-19): split off this file from plot.py (:trac:`12857`)
- Punarbasu Purkayastha (2012-05-20): Add logarithmic scale (:trac:`4529`)
- Emily Chen (2013-01-05): Add documentation for
:meth:`~sage.plot.graphics.Graphics.show` figsize parameter (:trac:`5956`)
- Eric Gourgoulhon (2015-03-19): Add parameter axes_labels_size (:trac:`18004`)
- Eric Gourgoulhon (2019-05-24): :class:`~sage.plot.multigraphics.GraphicsArray`
moved to new module :mod:`~sage.plot.multigraphics`; various improvements and
fixes in :meth:`Graphics.matplotlib` and ``Graphics._set_scale``; new method
:meth:`Graphics.inset`
"""
# ****************************************************************************
# Copyright (C) 2006 Alex Clemesha <[email protected]>
# Copyright (C) 2006-2008 William Stein <[email protected]>
# Copyright (C) 2010 Jason Grout
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************
import os
from collections.abc import Iterable
from math import isnan
import sage.misc.verbose
from sage.misc.temporary_file import tmp_filename
from sage.misc.fast_methods import WithEqualityById
from sage.structure.sage_object import SageObject
from sage.misc.decorators import suboptions
from .colors import rgbcolor
ALLOWED_EXTENSIONS = ['.eps', '.pdf', '.pgf', '.png', '.ps', '.sobj', '.svg']
DEFAULT_DPI = 100
# If do_verify is True, options are checked when drawing a
# GraphicsPrimitive. See primitive.py
do_verify = True
def is_Graphics(x):
"""
Return True if `x` is a Graphics object.
EXAMPLES::
sage: from sage.plot.graphics import is_Graphics
sage: is_Graphics(1)
False
sage: is_Graphics(disk((0.0, 0.0), 1, (0, pi/2)))
True
"""
return isinstance(x, Graphics)
def _parse_figsize(figsize):
r"""
Helper function to get a figure size in matplotlib format.
INPUT:
- ``figsize`` -- width or [width, height] in inches; if only the width is
provided, the height is computed from matplotlib's default aspect ratio
OUTPUT:
- a pair of ``float``'s representing ``(width, height)``
EXAMPLES::
sage: from sage.plot.graphics import _parse_figsize
sage: _parse_figsize([5, 4])
(5.0, 4.0)
The default aspect ratio is 4/3::
sage: _parse_figsize(5) # tol 1.0e-13
(5.0, 3.75)
"""
from matplotlib import rcParams
if isinstance(figsize, (list, tuple)):
# figsize should be a pair of positive numbers
if len(figsize) != 2:
raise ValueError("figsize should be a positive number or a list "
"of two positive numbers, not {0}".format(figsize))
figsize = (float(figsize[0]), float(figsize[1])) # floats for mpl
if not (figsize[0] > 0 and figsize[1] > 0):
raise ValueError("figsize should be positive numbers, "
"not {0} and {1}".format(figsize[0], figsize[1]))
else:
# in this case, figsize is a single number representing the width and
# should be positive
try:
figsize = float(figsize) # to pass to mpl
except TypeError:
raise TypeError("figsize should be a positive number, not {0}".format(figsize))
if figsize > 0:
default_width, default_height = rcParams['figure.figsize']
figsize = (figsize, default_height * figsize / default_width)
else:
raise ValueError("figsize should be positive, not {0}".format(figsize))
return figsize
class Graphics(WithEqualityById, SageObject):
"""
The Graphics object is an empty list of graphics objects. It is
useful to use this object when initializing a for loop where
different graphics object will be added to the empty object.
EXAMPLES::
sage: G = Graphics(); print(G)
Graphics object consisting of 0 graphics primitives
sage: c = circle((1,1), 1)
sage: G+=c; print(G)
Graphics object consisting of 1 graphics primitive
Here we make a graphic of embedded isosceles triangles, coloring
each one with a different color as we go::
sage: h=10; c=0.4; p=0.5
sage: G = Graphics()
sage: for x in srange(1,h+1):
....: l = [[0,x*sqrt(3)],[-x/2,-x*sqrt(3)/2],[x/2,-x*sqrt(3)/2],[0,x*sqrt(3)]]
....: G+=line(l,color=hue(c + p*(x/h)))
sage: G.show(figsize=[5,5])
We can change the scale of the axes in the graphics before displaying.::
sage: G = plot(exp, 1, 10) # long time
sage: G.show(scale='semilogy') # long time
TESTS:
From :trac:`4604`, ensure Graphics can handle 3d objects::
sage: g = Graphics()
sage: g += sphere((1, 1, 1), 2)
sage: g.show()
We check that graphics can be pickled (we can't use equality on
graphics so we just check that the load/dump cycle gives a
:class:`Graphics` instance)::
sage: g = Graphics()
sage: g2 = loads(dumps(g))
sage: g2.show()
::
sage: isinstance(g2, Graphics)
True
sage: hash(Graphics()) # random
42
.. automethod:: _rich_repr_
"""
def __init__(self):
"""
Create a new empty Graphics objects with all the defaults.
EXAMPLES::
sage: G = Graphics()
"""
self._axes_color = (0, 0, 0)
self._axes_label_color = (0, 0, 0)
self._axes_width = 0.8
self._bbox_extra_artists = []
self._extra_kwds = {}
self._fontsize = 10
self._axes_labels_size = 1.6
self._legend_colors = []
self._legend_opts = {}
self._objects = []
self._show_axes = True
self._show_legend = False
self._tick_label_color = (0, 0, 0)
def set_aspect_ratio(self, ratio):
"""
Set the aspect ratio, which is the ratio of height and width
of a unit square (i.e., height/width of a unit square), or
'automatic' (expand to fill the figure).
INPUT:
- ``ratio`` - a positive real number or 'automatic'
EXAMPLES: We create a plot of the upper half of a circle, but it
doesn't look round because the aspect ratio is off::
sage: P = plot(sqrt(1-x^2),(x,-1,1)); P
Graphics object consisting of 1 graphics primitive
So we set the aspect ratio and now it is round::
sage: P.set_aspect_ratio(1)
sage: P.aspect_ratio()
1.0
sage: P
Graphics object consisting of 1 graphics primitive
Note that the aspect ratio is inherited upon addition (which takes
the max of aspect ratios of objects whose aspect ratio has been
set)::
sage: P + plot(sqrt(4-x^2),(x,-2,2))
Graphics object consisting of 2 graphics primitives
In the following example, both plots produce a circle that looks
twice as tall as wide::
sage: Q = circle((0,0), 0.5); Q.set_aspect_ratio(2)
sage: (P + Q).aspect_ratio(); P+Q
2.0
Graphics object consisting of 2 graphics primitives
sage: (Q + P).aspect_ratio(); Q+P
2.0
Graphics object consisting of 2 graphics primitives
"""
if ratio != 'auto' and ratio != 'automatic':
ratio = float(ratio)
if ratio <= 0:
raise ValueError("the aspect ratio must be positive or 'automatic'")
else:
ratio = 'automatic'
self._extra_kwds['aspect_ratio'] = ratio
def aspect_ratio(self):
"""
Get the current aspect ratio, which is the ratio of height to
width of a unit square, or 'automatic'.
OUTPUT: a positive float (height/width of a unit square), or 'automatic'
(expand to fill the figure).
EXAMPLES:
The default aspect ratio for a new blank Graphics object is 'automatic'::
sage: P = Graphics()
sage: P.aspect_ratio()
'automatic'
The aspect ratio can be explicitly set different than the object's default::
sage: P = circle((1,1), 1)
sage: P.aspect_ratio()
1.0
sage: P.set_aspect_ratio(2)
sage: P.aspect_ratio()
2.0
sage: P.set_aspect_ratio('automatic')
sage: P.aspect_ratio()
'automatic'
"""
return self._extra_kwds.get('aspect_ratio', 'automatic')
def legend(self, show=None):
r"""
Set whether or not the legend is shown by default.
INPUT:
- ``show`` - (default: None) a boolean
If called with no input, return the current legend setting.
EXAMPLES:
By default no legend is displayed::
sage: P = plot(sin)
sage: P.legend()
False
But if we put a label then the legend is shown::
sage: P = plot(sin, legend_label='sin')
sage: P.legend()
True
We can turn it on or off::
sage: P.legend(False)
sage: P.legend()
False
sage: P.legend(True)
sage: P # show with the legend
Graphics object consisting of 1 graphics primitive
"""
if show is None:
return self._show_legend
else:
self._show_legend = bool(show)
def set_legend_options(self, **kwds):
r"""
Set various legend options.
INPUT:
- ``title`` - (default: None) string, the legend title
- ``ncol`` - (default: 1) positive integer, the number of columns
- ``columnspacing`` - (default: None) the spacing between columns
- ``borderaxespad`` - (default: None) float, length between the axes and the legend
- ``back_color`` - (default: 'white') This parameter can be a string
denoting a color or an RGB tuple. The string can be a color name
as in ('red', 'green', 'yellow', ...) or a floating point number
like '0.8' which gets expanded to (0.8, 0.8, 0.8). The
tuple form is just a floating point RGB tuple with all values ranging
from 0 to 1.
- ``handlelength`` - (default: 0.05) float, the length of the legend handles
- ``handletextpad`` - (default: 0.5) float, the pad between the legend handle and text
- ``labelspacing`` - (default: 0.02) float, vertical space between legend entries
- ``loc`` - (default: 'best') May be a string, an integer or a tuple. String or
integer inputs must be one of the following:
- 0, 'best'
- 1, 'upper right'
- 2, 'upper left'
- 3, 'lower left'
- 4, 'lower right'
- 5, 'right'
- 6, 'center left'
- 7, 'center right'
- 8, 'lower center'
- 9, 'upper center'
- 10, 'center'
- Tuple arguments represent an absolute (x, y) position on the plot
in axes coordinates (meaning from 0 to 1 in each direction).
- ``markerscale`` - (default: 0.6) float, how much to scale the markers in the legend.
- ``numpoints`` - (default: 2) integer, the number of points in the legend for line
- ``borderpad`` - (default: 0.6) float, the fractional whitespace inside the legend border
(between 0 and 1)
- ``font_family`` - (default: 'sans-serif') string, one of 'serif', 'sans-serif',
'cursive', 'fantasy', 'monospace'
- ``font_style`` - (default: 'normal') string, one of 'normal', 'italic', 'oblique'
- ``font_variant`` - (default: 'normal') string, one of 'normal', 'small-caps'
- ``font_weight`` - (default: 'medium') string, one of 'black', 'extra bold', 'bold',
'semibold', 'medium', 'normal', 'light'
- ``font_size`` - (default: 'medium') string, one of 'xx-small', 'x-small', 'small',
'medium', 'large', 'x-large', 'xx-large' or an absolute font size (e.g. 12)
- ``shadow`` - (default: True) boolean - draw a shadow behind the legend
- ``fancybox`` - (default: False) a boolean. If True, draws a frame with a round
fancybox.
These are all keyword arguments.
OUTPUT: a dictionary of all current legend options
EXAMPLES:
By default, no options are set::
sage: p = plot(tan, legend_label='tan')
sage: p.set_legend_options()
{}
We build a legend without a shadow::
sage: p.set_legend_options(shadow=False)
sage: p.set_legend_options()['shadow']
False
To set the legend position to the center of the plot, all these
methods are roughly equivalent::
sage: p.set_legend_options(loc='center'); p
Graphics object consisting of 1 graphics primitive
::
sage: p.set_legend_options(loc=10); p
Graphics object consisting of 1 graphics primitive
::
sage: p.set_legend_options(loc=(0.5,0.5)); p # aligns the bottom of the box to the center
Graphics object consisting of 1 graphics primitive
"""
if len(kwds) == 0:
return self._legend_opts
else:
self._legend_opts.update(kwds)
def get_axes_range(self):
"""
Returns a dictionary of the range of the axes for this graphics
object. This is fall back to the ranges in get_minmax_data() for
any value which the user has not explicitly set.
.. warning::
Changing the dictionary returned by this function does not
change the axes range for this object. To do that, use the
:meth:`set_axes_range` method.
EXAMPLES::
sage: L = line([(1,2), (3,-4), (2, 5), (1,2)])
sage: list(sorted(L.get_axes_range().items()))
[('xmax', 3.0), ('xmin', 1.0), ('ymax', 5.0), ('ymin', -4.0)]
sage: L.set_axes_range(xmin=-1)
sage: list(sorted(L.get_axes_range().items()))
[('xmax', 3.0), ('xmin', -1.0), ('ymax', 5.0), ('ymin', -4.0)]
"""
axes_range = self.get_minmax_data()
axes_range.update(self._get_axes_range_dict())
return axes_range
def set_axes_range(self, xmin=None, xmax=None, ymin=None, ymax=None):
"""
Set the ranges of the `x` and `y` axes.
INPUT:
- ``xmin, xmax, ymin, ymax`` - floats
EXAMPLES::
sage: L = line([(1,2), (3,-4), (2, 5), (1,2)])
sage: L.set_axes_range(-1, 20, 0, 2)
sage: d = L.get_axes_range()
sage: d['xmin'], d['xmax'], d['ymin'], d['ymax']
(-1.0, 20.0, 0.0, 2.0)
"""
l = locals()
axes_range = self._get_axes_range_dict()
for name in ['xmin', 'xmax', 'ymin', 'ymax']:
if l[name] is not None:
axes_range[name] = float(l[name])
axes_range = set_axes_range
def _get_axes_range_dict(self):
"""
Returns the underlying dictionary used to store the user's
custom ranges for the axes on this object.
EXAMPLES::
sage: L = line([(1,2), (3,-4), (2, 5), (1,2)])
sage: L._get_axes_range_dict()
{}
sage: L.set_axes_range(xmin=-1)
sage: L._get_axes_range_dict()
{'xmin': -1.0}
"""
try:
return self._axes_range
except AttributeError:
self._axes_range = {}
return self._axes_range
def set_flip(self, flip_x=None, flip_y=None):
"""
Set the flip options for this graphics object.
INPUT:
- ``flip_x`` -- boolean (default: ``None``); if not ``None``, set the
``flip_x`` option to this value
- ``flip_y`` -- boolean (default: ``None``); if not ``None``, set the
``flip_y`` option to this value
EXAMPLES::
sage: L = line([(1, 0), (2, 3)])
sage: L.set_flip(flip_y=True)
sage: L.flip()
(False, True)
sage: L.set_flip(True, False)
sage: L.flip()
(True, False)
"""
if flip_x is not None:
self._extra_kwds['flip_x'] = flip_x
if flip_y is not None:
self._extra_kwds['flip_y'] = flip_y
def flip(self, flip_x=False, flip_y=False):
"""
Get the flip options and optionally mirror this graphics object.
INPUT:
- ``flip_x`` -- boolean (default: ``False``); if ``True``, replace the
current ``flip_x`` option by its opposite
- ``flip_y`` -- boolean (default: ``False``); if ``True``, replace the
current ``flip_y`` option by its opposite
OUTPUT: a tuple containing the new flip options
EXAMPLES:
When called without arguments, this just returns the current flip
options::
sage: L = line([(1, 0), (2, 3)])
sage: L.flip()
(False, False)
Otherwise, the specified options are changed and the new options are
returned::
sage: L.flip(flip_y=True)
(False, True)
sage: L.flip(True, True)
(True, False)
"""
a = self._extra_kwds.get('flip_x', self.SHOW_OPTIONS['flip_x'])
b = self._extra_kwds.get('flip_y', self.SHOW_OPTIONS['flip_y'])
if flip_x:
a = not a
self._extra_kwds['flip_x'] = a
if flip_y:
b = not b
self._extra_kwds['flip_y'] = b
return (a, b)
def fontsize(self, s=None):
"""
Set the font size of axes labels and tick marks.
Note that the relative size of the axes labels font w.r.t. the tick
marks font can be adjusted via :meth:`axes_labels_size`.
INPUT:
- ``s`` - integer, a font size in points.
If called with no input, return the current fontsize.
EXAMPLES::
sage: L = line([(1,2), (3,-4), (2, 5), (1,2)])
sage: L.fontsize()
10
sage: L.fontsize(20)
sage: L.fontsize()
20
All the numbers on the axes will be very large in this plot::
sage: L
Graphics object consisting of 1 graphics primitive
"""
if s is None:
try:
return self._fontsize
except AttributeError:
self._fontsize = 10
return self._fontsize
self._fontsize = int(s)
def axes_labels_size(self, s=None):
"""
Set the relative size of axes labels w.r.t. the axes tick marks.
INPUT:
- ``s`` - float, relative size of axes labels w.r.t. to the tick marks,
the size of the tick marks being set by :meth:`fontsize`.
If called with no input, return the current relative size.
EXAMPLES::
sage: p = plot(sin(x^2), (x, -3, 3), axes_labels=['$x$','$y$'])
sage: p.axes_labels_size() # default value
1.6
sage: p.axes_labels_size(2.5)
sage: p.axes_labels_size()
2.5
Now the axes labels are large w.r.t. the tick marks::
sage: p
Graphics object consisting of 1 graphics primitive
"""
if s is None:
try:
return self._axes_labels_size
except AttributeError:
self._axes_labels_size = 1.6
return self._axes_labels_size
self._axes_labels_size = float(s)
def axes(self, show=None):
"""
Set whether or not the `x` and `y` axes are shown
by default.
INPUT:
- ``show`` - bool
If called with no input, return the current axes setting.
EXAMPLES::
sage: L = line([(1,2), (3,-4), (2, 5), (1,2)])
By default the axes are displayed.
::
sage: L.axes()
True
But we turn them off, and verify that they are off
::
sage: L.axes(False)
sage: L.axes()
False
Displaying L now shows a triangle but no axes.
::
sage: L
Graphics object consisting of 1 graphics primitive
"""
if show is None:
try:
return self._show_axes
except AttributeError:
self._show_axes = True
return self._show_axes
self._show_axes = bool(show)
def axes_color(self, c=None):
"""
Set the axes color.
If called with no input, return the current axes_color setting.
INPUT:
- ``c`` - an RGB color 3-tuple, where each tuple entry
is a float between 0 and 1
EXAMPLES: We create a line, which has like everything a default
axes color of black.
::
sage: L = line([(1,2), (3,-4), (2, 5), (1,2)])
sage: L.axes_color()
(0, 0, 0)
We change the axes color to red and verify the change.
::
sage: L.axes_color((1,0,0))
sage: L.axes_color()
(1.0, 0.0, 0.0)
When we display the plot, we'll see a blue triangle and bright red
axes.
::
sage: L
Graphics object consisting of 1 graphics primitive
"""
if c is None:
try:
return self._axes_color
except AttributeError:
self._axes_color = (0.0, 0.0, 0.0)
return self._axes_color
self._axes_color = rgbcolor(c)
def axes_labels(self, l=None):
"""
Set the axes labels.
INPUT:
- ``l`` - (default: None) a list of two strings or
None
OUTPUT: a 2-tuple of strings
If l is None, returns the current ``axes_labels``,
which is itself by default None. The default labels are both
empty.
EXAMPLES: We create a plot and put x and y axes labels on it.
::
sage: p = plot(sin(x), (x, 0, 10))
sage: p.axes_labels(['$x$','$y$'])
sage: p.axes_labels()
('$x$', '$y$')
Now when you plot p, you see x and y axes labels::
sage: p
Graphics object consisting of 1 graphics primitive
Notice that some may prefer axes labels which are not
typeset::
sage: plot(sin(x), (x, 0, 10), axes_labels=['x','y'])
Graphics object consisting of 1 graphics primitive
TESTS:
Unicode strings are acceptable; see :trac:`13161`. Note that
this does not guarantee that matplotlib will handle the strings
properly, although it should.
::
sage: c = circle((0,0), 1)
sage: c.axes_labels(['axe des abscisses', 'axe des ordonnées'])
sage: c._axes_labels
('axe des abscisses', 'axe des ordonnées')
"""
if l is None:
try:
return self._axes_labels
except AttributeError:
self._axes_labels = None
return self._axes_labels
if not isinstance(l, (list, tuple)):
raise TypeError("l must be a list or tuple")
if len(l) != 2:
raise ValueError("l must have length 2")
self._axes_labels = tuple(l)
def axes_label_color(self, c=None):
r"""
Set the color of the axes labels.
The axes labels are placed at the edge of the x and y axes, and are
not on by default (use the ``axes_labels`` command to
set them; see the example below). This function just changes their
color.
INPUT:
- ``c`` - an RGB 3-tuple of numbers between 0 and 1
If called with no input, return the current axes_label_color
setting.
EXAMPLES: We create a plot, which by default has axes label color
black.
::
sage: p = plot(sin, (-1,1))
sage: p.axes_label_color()
(0, 0, 0)
We change the labels to be red, and confirm this::
sage: p.axes_label_color((1,0,0))
sage: p.axes_label_color()
(1.0, 0.0, 0.0)
We set labels, since otherwise we won't see anything.
::
sage: p.axes_labels(['$x$ axis', '$y$ axis'])
In the plot below, notice that the labels are red::
sage: p
Graphics object consisting of 1 graphics primitive
"""
if c is None:
try:
return self._axes_label_color
except AttributeError:
self._axes_label_color = (0, 0, 0)
return self._axes_label_color
self._axes_label_color = rgbcolor(c)
def axes_width(self, w=None):
r"""
Set the axes width. Use this to draw a plot with really fat or
really thin axes.
INPUT:
- ``w`` - a float
If called with no input, return the current
``axes_width`` setting.
EXAMPLES: We create a plot, see the default axes width (with funny
Python float rounding), then reset the width to 10 (very fat).
::
sage: p = plot(cos, (-3,3))
sage: p.axes_width()
0.8
sage: p.axes_width(10)
sage: p.axes_width()
10.0
Finally we plot the result, which is a graph with very fat axes.
::
sage: p
Graphics object consisting of 1 graphics primitive
"""
if w is None:
try:
return self._axes_width
except AttributeError:
self._axes_width = True
return self._axes_width
self._axes_width = float(w)
def tick_label_color(self, c=None):
"""
Set the color of the axes tick labels.
INPUT:
- ``c`` - an RGB 3-tuple of numbers between 0 and 1
If called with no input, return the current tick_label_color
setting.
EXAMPLES::
sage: p = plot(cos, (-3,3))
sage: p.tick_label_color()
(0, 0, 0)
sage: p.tick_label_color((1,0,0))
sage: p.tick_label_color()
(1.0, 0.0, 0.0)
sage: p
Graphics object consisting of 1 graphics primitive
"""
if c is None:
try:
return self._tick_label_color
except AttributeError:
self._tick_label_color = (0, 0, 0)
return self._tick_label_color
self._tick_label_color = rgbcolor(c)
def _repr_(self):
r"""
Return a string representation of the graphics objects.
OUTPUT:
String.
EXAMPLES:
We create a plot and call :meth:`show` on it, which causes it
to be displayed as a plot::
sage: P = plot(cos, (-1,1))
sage: P.show()
Just doing this also displays the plot::
sage: P
Graphics object consisting of 1 graphics primitive
Using the Python `repr` or `str` commands do not display the
plot::
sage: repr(P)
'Graphics object consisting of 1 graphics primitive'
sage: str(P)
'Graphics object consisting of 1 graphics primitive'
sage: print(P)
Graphics object consisting of 1 graphics primitive
TESTS::
sage: P._repr_()
'Graphics object consisting of 1 graphics primitive'
"""
return str(self)
def _rich_repr_(self, display_manager, **kwds):
"""
Rich Output Magic Method
See :mod:`sage.repl.rich_output` for details.
EXAMPLES::
sage: from sage.repl.rich_output import get_display_manager
sage: dm = get_display_manager()
sage: g = Graphics()
sage: g._rich_repr_(dm)
OutputImagePng container
"""
types = display_manager.types
prefer_raster = (
('.png', types.OutputImagePng),
('.jpg', types.OutputImageJpg),
('.gif', types.OutputImageGif),
)
prefer_vector = (
('.svg', types.OutputImageSvg),
('.pdf', types.OutputImagePdf),
)
graphics = display_manager.preferences.graphics
if graphics == 'disable':
return
elif graphics == 'raster' or graphics is None:
preferred = prefer_raster + prefer_vector
elif graphics == 'vector':
preferred = prefer_vector + prefer_raster
else:
raise ValueError('unknown graphics output preference')
for file_ext, output_container in preferred:
if output_container in display_manager.supported_output():