-
-
Notifications
You must be signed in to change notification settings - Fork 838
Expand file tree
/
Copy pathplot.py
More file actions
4182 lines (3093 loc) · 142 KB
/
plot.py
File metadata and controls
4182 lines (3093 loc) · 142 KB
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
# sage.doctest: needs sage.symbolic
r"""
2D plotting
Sage provides extensive 2D plotting functionality. The underlying
rendering is done using the matplotlib Python library.
The following graphics primitives are supported:
- :func:`~sage.plot.arrow.arrow` -- an arrow from a min point to a max point
- :func:`~sage.plot.circle.circle` -- a circle with given radius
- :func:`~sage.plot.ellipse.ellipse` -- an ellipse with given radii
and angle
- :func:`~sage.plot.arc.arc` -- an arc of a circle or an ellipse
- :func:`~sage.plot.disk.disk` -- a filled disk (i.e. a sector or wedge of a circle)
- :func:`~sage.plot.line.line` -- a line determined by a sequence of points (this need not
be straight!)
- :func:`~sage.plot.point.point` -- a point
- :func:`~sage.plot.text.text` -- some text
- :func:`~sage.plot.polygon.polygon` -- a filled polygon
The following plotting functions are supported:
- :func:`plot` -- plot of a function or other Sage object (e.g., elliptic
curve)
- :func:`parametric_plot`
- :func:`~sage.plot.contour_plot.implicit_plot`
- :func:`polar_plot`
- :func:`~sage.plot.contour_plot.region_plot`
- :func:`list_plot`
- :func:`~sage.plot.scatter_plot.scatter_plot`
- :func:`~sage.plot.bar_chart.bar_chart`
- :func:`~sage.plot.contour_plot.contour_plot`
- :func:`~sage.plot.density_plot.density_plot`
- :func:`~sage.plot.plot_field.plot_vector_field`
- :func:`~sage.plot.plot_field.plot_slope_field`
- :func:`~sage.plot.matrix_plot.matrix_plot`
- :func:`~sage.plot.complex_plot.complex_plot`
- :func:`graphics_array`
- :func:`multi_graphics`
- The following log plotting functions:
- :func:`plot_loglog`
- :func:`plot_semilogx` and :func:`plot_semilogy`
- :func:`list_plot_loglog`
- :func:`list_plot_semilogx` and :func:`list_plot_semilogy`
The following miscellaneous Graphics functions are included:
- :func:`~sage.plot.graphics.Graphics`
- :func:`~sage.plot.graphics.is_Graphics`
- :func:`~sage.plot.colors.hue`
Type ``?`` after each primitive in Sage for help and examples.
EXAMPLES:
We draw a curve::
sage: plot(x^2, (x,0,5))
Graphics object consisting of 1 graphics primitive
.. PLOT::
g = plot(x**2, (x,0,5))
sphinx_plot(g)
We draw a circle and a curve::
sage: circle((1,1), 1) + plot(x^2, (x,0,5))
Graphics object consisting of 2 graphics primitives
.. PLOT::
g = circle((1,1), 1) + plot(x**2, (x,0,5))
sphinx_plot(g)
Notice that the aspect ratio of the above plot makes the plot very tall
because the plot adopts the default aspect ratio of the circle (to make
the circle appear like a circle). We can change the aspect ratio to be
what we normally expect for a plot by explicitly asking for an
'automatic' aspect ratio::
sage: show(circle((1,1), 1) + plot(x^2, (x,0,5)), aspect_ratio='automatic')
The aspect ratio describes the apparently height/width ratio of a unit
square. If you want the vertical units to be twice as big as the
horizontal units, specify an aspect ratio of 2::
sage: show(circle((1,1), 1) + plot(x^2, (x,0,5)), aspect_ratio=2)
The ``figsize`` option adjusts the figure size. The default figsize is
4. To make a figure that is roughly twice as big, use ``figsize=8``::
sage: show(circle((1,1), 1) + plot(x^2, (x,0,5)), figsize=8)
You can also give separate horizontal and vertical dimensions. Both
will be measured in inches::
sage: show(circle((1,1), 1) + plot(x^2, (x,0,5)), figsize=[4,8])
However, do not make the figsize too big (e.g. one dimension greater
than 327 or both in the mid-200s) as this will lead to errors or crashes.
See :meth:`~sage.plot.graphics.Graphics.show` for full details.
Note that the axes will not cross if the data is not on both sides of
both axes, even if it is quite close::
sage: plot(x^3, (x,1,10))
Graphics object consisting of 1 graphics primitive
.. PLOT::
g = plot(x**3, (x,1,10))
sphinx_plot(g)
When the labels have quite different orders of magnitude or are very
large, scientific notation (the `e` notation for powers of ten) is used::
sage: plot(x^2, (x,480,500)) # no scientific notation
Graphics object consisting of 1 graphics primitive
.. PLOT::
g = plot(x**2, (x,480,500))
sphinx_plot(g)
::
sage: plot(x^2, (x,300,500)) # scientific notation on y-axis
Graphics object consisting of 1 graphics primitive
.. PLOT::
g = plot(x**2, (x,300,500))
sphinx_plot(g)
But you can fix your own tick labels, if you know what to expect and
have a preference::
sage: plot(x^2, (x,300,500), ticks=[100,50000])
Graphics object consisting of 1 graphics primitive
.. PLOT::
g = plot(x**2, (x,300,500), ticks=[100,50000])
sphinx_plot(g)
To change the ticks on one axis only, use the following notation::
sage: plot(x^2, (x,300,500), ticks=[None,50000])
Graphics object consisting of 1 graphics primitive
.. PLOT::
g = plot(x**2, (x,300,500), ticks=[None,50000])
sphinx_plot(g)
You can even have custom tick labels along with custom positioning. ::
sage: plot(x^2, (x,0,3), ticks=[[1,2.5],pi/2], tick_formatter=[["$x_1$","$x_2$"],pi]) # long time
Graphics object consisting of 1 graphics primitive
.. PLOT::
g = plot(x**2, (x,0,3), ticks=[[1,2.5],pi/2], tick_formatter=[["$x_1$","$x_2$"],pi])
sphinx_plot(g)
We construct a plot involving several graphics objects::
sage: G = plot(cos(x), (x, -5, 5), thickness=5, color='green', title='A plot')
sage: P = polygon([[1,2], [5,6], [5,0]], color='red')
sage: G + P
Graphics object consisting of 2 graphics primitives
.. PLOT::
G = plot(cos(x), (x, -5, 5), thickness=5, color='green', title='A plot')
P = polygon([[1,2], [5,6], [5,0]], color='red')
sphinx_plot(G + P)
Next we construct the reflection of the above polygon about the
`y`-axis by iterating over the list of first-coordinates of
the first graphic element of ``P`` (which is the actual
Polygon; note that ``P`` is a Graphics object, which consists
of a single polygon)::
sage: Q = polygon([(-x,y) for x,y in P[0]], color='blue')
sage: Q # show it
Graphics object consisting of 1 graphics primitive
.. PLOT::
P = polygon([[1,2], [5,6], [5,0]], color='red')
Q = polygon([(-x,y) for x,y in P[0]], color='blue')
sphinx_plot(Q)
We combine together different graphics objects using "+"::
sage: H = G + P + Q
sage: print(H)
Graphics object consisting of 3 graphics primitives
sage: type(H)
<class 'sage.plot.graphics.Graphics'>
sage: H[1]
Polygon defined by 3 points
sage: list(H[1])
[(1.0, 2.0), (5.0, 6.0), (5.0, 0.0)]
sage: H # show it
Graphics object consisting of 3 graphics primitives
.. PLOT::
G = plot(cos(x), (x, -5, 5), thickness=5, color='green', title='A plot')
P = polygon([[1,2], [5,6], [5,0]], color='red')
Q = polygon([(-x,y) for x,y in P[0]], color='blue')
H = G + P + Q
sphinx_plot(H)
We can put text in a graph::
sage: L = [[cos(pi*i/100)^3,sin(pi*i/100)] for i in range(200)]
sage: p = line(L, rgbcolor=(1/4,1/8,3/4))
sage: tt = text('A Bulb', (1.5, 0.25))
sage: tx = text('x axis', (1.5,-0.2))
sage: ty = text('y axis', (0.4,0.9))
sage: g = p + tt + tx + ty
sage: g.show(xmin=-1.5, xmax=2, ymin=-1, ymax=1)
.. PLOT::
L = [[cos(pi*i/100)**3,sin(pi*i/100)] for i in range(200)]
p = line(L, rgbcolor=(1.0/4.0,1.0/8.0,3.0/4.0))
t = text('A Bulb', (1.5, 0.25))
x = text('x axis', (1.5,-0.2))
y = text('y axis', (0.4,0.9))
g = p+t+x+y
g.xmin(-1.5)
g.xmax(2)
g.ymin(-1)
g.ymax(1)
sphinx_plot(g)
We can add a graphics object to another one as an inset::
sage: g1 = plot(x^2*sin(1/x), (x, -2, 2), axes_labels=['$x$', '$y$'])
sage: g2 = plot(x^2*sin(1/x), (x, -0.3, 0.3), axes_labels=['$x$', '$y$'],
....: frame=True)
sage: g1.inset(g2, pos=(0.15, 0.7, 0.25, 0.25))
Multigraphics with 2 elements
.. PLOT::
g1 = plot(x**2*sin(1/x), (x, -2, 2), axes_labels=['$x$', '$y$'])
g2 = plot(x**2*sin(1/x), (x, -0.3, 0.3), axes_labels=['$x$', '$y$'], \
frame=True)
sphinx_plot(g1.inset(g2, pos=(0.15, 0.7, 0.25, 0.25)))
We can add a title to a graph::
sage: plot(x^2, (x,-2,2), title='A plot of $x^2$')
Graphics object consisting of 1 graphics primitive
.. PLOT::
g=plot(x**2, (x,-2,2), title='A plot of $x^2$')
sphinx_plot(g)
We can set the position of the title::
sage: plot(x^2, (-2,2), title='Plot of $x^2$', title_pos=(0.5,-0.05))
Graphics object consisting of 1 graphics primitive
.. PLOT::
g=plot(x**2, (-2,2), title='Plot of $x^2$', title_pos=(0.5,-0.05))
sphinx_plot(g)
We plot the Riemann zeta function along the critical line and see
the first few zeros::
sage: i = CDF.0 # define i this way for maximum speed.
sage: p1 = plot(lambda t: arg(zeta(0.5+t*i)), 1, 27, rgbcolor=(0.8,0,0))
sage: p2 = plot(lambda t: abs(zeta(0.5+t*i)), 1, 27, color=hue(0.7))
sage: print(p1 + p2)
Graphics object consisting of 2 graphics primitives
sage: p1 + p2 # display it
Graphics object consisting of 2 graphics primitives
.. PLOT::
from sage.rings.complex_double import ComplexDoubleElement
i = ComplexDoubleElement(0,1) # define i this way for maximum speed.
p1 = plot(lambda t: arg(zeta(0.5+t*i)), 1, 27, rgbcolor=(0.8,0,0))
p2 = plot(lambda t: abs(zeta(0.5+t*i)), 1, 27, color=hue(0.7))
g = p1 + p2
sphinx_plot(g)
.. NOTE::
Not all functions in Sage are symbolic. When plotting non-symbolic functions
they should be wrapped in ``lambda``::
sage: plot(lambda x:fibonacci(round(x)), (x,1,10))
Graphics object consisting of 1 graphics primitive
.. PLOT::
g=plot(lambda x:fibonacci(round(x)), (x,1,10))
sphinx_plot(g)
Many concentric circles shrinking toward the origin::
sage: show(sum(circle((i,0), i, hue=sin(i/10)) for i in [10,9.9,..,0])) # long time
.. PLOT::
g = sum(circle((i,0), i, hue=sin(i/10)) for i in srange(0,10,0.1))
sphinx_plot(g)
Here is a pretty graph::
sage: g = Graphics()
sage: for i in range(60):
....: p = polygon([(i*cos(i),i*sin(i)), (0,i), (i,0)],\
....: color=hue(i/40+0.4), alpha=0.2)
....: g = g + p
sage: g.show(dpi=200, axes=False)
.. PLOT::
g=Graphics()
for i in range(60):
# i/40 doesn't convert to real number
p = polygon([(i*cos(i),i*sin(i)), (0,i), (i,0)],\
color=hue(0.025*i+0.4), alpha=0.2)
g = g + p
g.axes(False)
sphinx_plot(g)
Another graph::
sage: x = var('x')
sage: P = plot(sin(x)/x, -4, 4, color='blue') + \
....: plot(x*cos(x), -4, 4, color='red') + \
....: plot(tan(x), -4, 4, color='green')
sage: P.show(ymin=-pi, ymax=pi)
.. PLOT::
g = plot(sin(x)/x, -4, 4, color='blue') + \
plot(x*cos(x), -4, 4, color='red') + \
plot(tan(x), -4, 4, color='green')
g.ymin(-pi)
g.ymax(pi)
sphinx_plot(g)
PYX EXAMPLES: These are some examples of plots similar to some of
the plots in the PyX (http://pyx.sourceforge.net) documentation:
Symbolline::
sage: y(x) = x*sin(x^2)
sage: v = [(x, y(x)) for x in [-3,-2.95,..,3]]
sage: show(points(v, rgbcolor=(0.2,0.6, 0.1), pointsize=30) + plot(spline(v), -3.1, 3))
.. PLOT::
#y(x)=x*sin(x**2) gave SyntaxError: can't assign to function call
def y(x): return x*sin(x**2)
v=list()
for x in srange(-3,3,0.05):
v.append((x, y(x)))
g = points(v, rgbcolor=(0.2,0.6, 0.1), pointsize=30) + plot(spline(v), -3.1, 3)
sphinx_plot(g)
Cycliclink::
sage: g1 = plot(cos(20*x)*exp(-2*x), 0, 1)
sage: g2 = plot(2*exp(-30*x) - exp(-3*x), 0, 1)
sage: show(graphics_array([g1, g2], 2, 1))
.. PLOT::
g1 = plot(cos(20*x)*exp(-2*x), 0, 1)
g2 = plot(2*exp(-30*x) - exp(-3*x), 0, 1)
g = graphics_array([g1, g2], 2, 1)
sphinx_plot(g)
Pi Axis::
sage: g1 = plot(sin(x), 0, 2*pi)
sage: g2 = plot(cos(x), 0, 2*pi, linestyle='--')
sage: (g1 + g2).show(ticks=pi/6, # show their sum, nicely formatted # long time
....: tick_formatter=pi)
.. PLOT::
g1 = plot(sin(x), 0, 2*pi, ticks=pi/6, tick_formatter=pi)
g2 = plot(cos(x), 0, 2*pi, linestyle='--', ticks=pi/6, tick_formatter=pi)
sphinx_plot(g1+g2)
An illustration of integration::
sage: f(x) = (x-3)*(x-5)*(x-7)+40
sage: P = line([(2,0),(2,f(2))], color='black')
sage: P += line([(8,0),(8,f(8))], color='black')
sage: P += polygon([(2,0),(2,f(2))] + [(x, f(x)) for x in [2,2.1,..,8]] + [(8,0),(2,0)],
....: rgbcolor=(0.8,0.8,0.8), aspect_ratio='automatic')
sage: P += text("$\\int_{a}^b f(x) dx$", (5, 20), fontsize=16, color='black')
sage: P += plot(f, (1, 8.5), thickness=3)
sage: P # show the result
Graphics object consisting of 5 graphics primitives
.. PLOT::
#inline f substitution to avoid SyntaxError: can't assign to function call in sphinx_plot
def f(x): return (x-3)*(x-5)*(x-7)+40
P = line([(2,0),(2,f(2))], color='black')
P = P + line([(8,0),(8,f(8))], color='black')
L = list(((2,0), (2,f(2))))
for i in srange(2,8.1,0.1):
L.append((i,f(i)))
L.append((8,0))
L.append((2,0))
P = P + polygon(L, rgbcolor=(0.8,0.8,0.8), aspect_ratio='automatic')
P = P + text("$\\int_{a}^b f(x) dx$", (5, 20), fontsize=16, color='black')
P = P + plot(f, (1, 8.5), thickness=3)
sphinx_plot(P)
NUMERICAL PLOTTING:
Sage includes Matplotlib, which provides 2D plotting with an interface
that is a likely very familiar to people doing numerical
computation.
You can use ``plt.clf()`` to clear the current image frame
and ``plt.close()`` to close it.
For example,
::
sage: import pylab as plt
sage: t = plt.arange(0.0, 2.0, 0.01)
sage: s = sin(2*pi*t)
sage: P = plt.plot(t, s, linewidth=1.0)
sage: xl = plt.xlabel('time (s)')
sage: yl = plt.ylabel('voltage (mV)')
sage: t = plt.title('About as simple as it gets, folks')
sage: plt.grid(True)
sage: import tempfile
sage: with tempfile.NamedTemporaryFile(suffix='.png') as f1:
....: plt.savefig(f1.name)
sage: plt.clf()
sage: with tempfile.NamedTemporaryFile(suffix='.png') as f2:
....: plt.savefig(f2.name)
sage: plt.close()
sage: plt.imshow([[1,2],[0,1]])
<matplotlib.image.AxesImage object at ...>
We test that ``imshow`` works as well, verifying that
:issue:`2900` is fixed (in Matplotlib).
::
sage: plt.imshow([[(0.0,0.0,0.0)]])
<matplotlib.image.AxesImage object at ...>
sage: import tempfile
sage: with tempfile.NamedTemporaryFile(suffix='.png') as f:
....: plt.savefig(f.name)
Since the above overwrites many Sage plotting functions, we reset
the state of Sage, so that the examples below work!
::
sage: reset()
See https://matplotlib.org/stable/ for complete documentation
about how to use Matplotlib.
TESTS:
We test dumping and loading a plot.
::
sage: p = plot(sin(x), (x, 0,2*pi))
sage: Q = loads(dumps(p))
Verify that a clean sage startup does *not* import matplotlib::
sage: os.system("sage -c \"if 'matplotlib' in sys.modules: sys.exit(1)\"") # long time
0
Verify that :issue:`10980` is fixed::
sage: plot(x,0,2,gridlines=([sqrt(2)],[]))
Graphics object consisting of 1 graphics primitive
AUTHORS:
- Alex Clemesha and William Stein (2006-04-10): initial version
- David Joyner: examples
- Alex Clemesha (2006-05-04) major update
- William Stein (2006-05-29): fine tuning, bug fixes, better server
integration
- William Stein (2006-07-01): misc polish
- Alex Clemesha (2006-09-29): added contour_plot, frame axes, misc
polishing
- Robert Miller (2006-10-30): tuning, NetworkX primitive
- Alex Clemesha (2006-11-25): added plot_vector_field, matrix_plot,
arrow, bar_chart, Axes class usage (see axes.py)
- Bobby Moretti and William Stein (2008-01): Change plot to specify
ranges using the (varname, min, max) notation.
- William Stein (2008-01-19): raised the documentation coverage from a
miserable 12 percent to a 'wopping' 35 percent, and fixed and
clarified numerous small issues.
- Jason Grout (2009-09-05): shifted axes and grid functionality over
to matplotlib; fixed a number of smaller issues.
- Jason Grout (2010-10): rewrote aspect ratio portions of the code
- Jeroen Demeyer (2012-04-19): move parts of this file to graphics.py (:issue:`12857`)
- Aaron Lauve (2016-07-13): reworked handling of 'color' when passed
a list of functions; now more in-line with other CAS's. Added list functionality
to linestyle and legend_label options as well. (:issue:`12962`)
- Eric Gourgoulhon (2019-04-24): add :func:`multi_graphics` and insets
"""
# ****************************************************************************
# Copyright (C) 2006 Alex Clemesha <clemesha@gmail.com>
# Copyright (C) 2006-2008 William Stein <wstein@gmail.com>
# 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/
# ****************************************************************************
from functools import reduce
# IMPORTANT: Do *not* import matplotlib at module scope. It takes a
# surprisingly long time to initialize itself. It's better if it is
# imported in functions, so it only gets started if it is actually
# going to be used.
# DEFAULT_FIGSIZE=(6, 3.70820393249937)
import sage.misc.verbose
from sage.arith.srange import srange
from sage.misc.randstate import current_randstate # for plot adaptive refinement
from math import sin, cos, pi, log, exp # for polar_plot and log scaling
from sage.ext.fast_eval import fast_float, is_fast_float
from sage.structure.element import Expression
from sage.misc.decorators import options
from .graphics import Graphics
from .multigraphics import GraphicsArray, MultiGraphics
from sage.plot.polygon import polygon
# import of line2d below is only for redirection of imports
from sage.plot.line import line
from sage.misc.lazy_import import lazy_import
lazy_import('sage.plot.line', 'line2d', deprecation=28717)
# Currently not used - see comment immediately above about
# figure.canvas.mpl_connect('draw_event', pad_for_tick_labels)
# TODO - figure out how to use this, add documentation
# def pad_for_tick_labels(event):
# import matplotlib.transforms as mtransforms
# figure=event.canvas.figure
# bboxes = []
# for ax in figure.axes:
# bbox = ax.xaxis.get_label().get_window_extent()
# # the figure transform goes from relative coords->pixels and we
# # want the inverse of that
# bboxi = bbox.inverse_transformed(figure.transFigure)
# bboxes.append(bboxi)
#
# bbox = ax.yaxis.get_label().get_window_extent()
# bboxi = bbox.inverse_transformed(figure.transFigure)
# bboxes.append(bboxi)
# for label in (ax.get_xticklabels()+ax.get_yticklabels() \
# + ax.get_xticklabels(minor=True) \
# +ax.get_yticklabels(minor=True)):
# bbox = label.get_window_extent()
# bboxi = bbox.inverse_transformed(figure.transFigure)
# bboxes.append(bboxi)
#
# # this is the bbox that bounds all the bboxes, again in relative
# # figure coords
# bbox = mtransforms.Bbox.union(bboxes)
# adjusted=adjust_figure_to_contain_bbox(figure,bbox)
#
# if adjusted:
# figure.canvas.draw()
# return False
#
# Currently not used - see comment above about
# figure.canvas.mpl_connect('draw_event', pad_for_tick_labels)
# TODO - figure out how to use this, add documentation
# def adjust_figure_to_contain_bbox(fig, bbox, pad=1.1):
# """
# For each amount we are over (in axes coordinates), we adjust by over*pad
# to give ourselves a bit of padding.
# """
# left=fig.subplotpars.left
# bottom=fig.subplotpars.bottom
# right=fig.subplotpars.right
# top=fig.subplotpars.top
#
# adjusted=False
# if bbox.xmin<0:
# left-=bbox.xmin*pad
# adjusted=True
# if bbox.ymin<0:
# bottom-=bbox.ymin*pad
# adjusted=True
# if bbox.xmax>1:
# right-=(bbox.xmax-1)*pad
# adjusted=True
# if bbox.ymax>1:
# top-=(bbox.ymax-1)*pad
# adjusted=True
#
# if left<right and bottom<top:
# fig.subplots_adjust(left=left, bottom=bottom, right=right, top=top)
# return adjusted
# else:
# return False
_SelectiveFormatterClass = None
def SelectiveFormatter(formatter, skip_values):
"""
This matplotlib formatter selectively omits some tick values and
passes the rest on to a specified formatter.
EXAMPLES:
This example is almost straight from a matplotlib example.
::
sage: # needs numpy
sage: from sage.plot.plot import SelectiveFormatter
sage: import matplotlib.pyplot as plt
sage: import numpy
sage: fig = plt.figure()
sage: ax = fig.add_subplot(111)
sage: t = numpy.arange(0.0, 2.0, 0.01)
sage: s = numpy.sin(2*numpy.pi*t)
sage: p = ax.plot(t, s)
sage: formatter = SelectiveFormatter(ax.xaxis.get_major_formatter(),
....: skip_values=[0,1])
sage: ax.xaxis.set_major_formatter(formatter)
sage: import tempfile
sage: with tempfile.NamedTemporaryFile(suffix='.png') as f:
....: fig.savefig(f.name)
"""
global _SelectiveFormatterClass
if _SelectiveFormatterClass is None:
from matplotlib.ticker import Formatter
class _SelectiveFormatterClass(Formatter):
def __init__(self, formatter, skip_values):
"""
Initialize a SelectiveFormatter object.
INPUT:
- ``formatter`` -- the formatter object to which we should pass labels
- ``skip_values`` -- list of values that we should skip when
formatting the tick labels
EXAMPLES::
sage: # needs numpy
sage: from sage.plot.plot import SelectiveFormatter
sage: import matplotlib.pyplot as plt
sage: import numpy
sage: fig = plt.figure()
sage: ax = fig.add_subplot(111)
sage: t = numpy.arange(0.0, 2.0, 0.01)
sage: s = numpy.sin(2*numpy.pi*t)
sage: line = ax.plot(t, s)
sage: formatter = SelectiveFormatter(ax.xaxis.get_major_formatter(),
....: skip_values=[0,1])
sage: ax.xaxis.set_major_formatter(formatter)
sage: from tempfile import NamedTemporaryFile
sage: with NamedTemporaryFile(suffix='.png') as f:
....: fig.savefig(f.name)
"""
self.formatter = formatter
self.skip_values = skip_values
def set_locs(self, locs):
"""
Set the locations for the ticks that are not skipped.
EXAMPLES::
sage: from sage.plot.plot import SelectiveFormatter
sage: import matplotlib.ticker
sage: formatter = SelectiveFormatter(matplotlib.ticker.Formatter(),
....: skip_values=[0,200])
sage: formatter.set_locs([i*100 for i in range(10)])
"""
self.formatter.set_locs([l for l in locs if l not in self.skip_values])
def __call__(self, x, *args, **kwds):
"""
Return the format for tick val *x* at position *pos*.
EXAMPLES::
sage: from sage.plot.plot import SelectiveFormatter
sage: import matplotlib.ticker
sage: formatter = SelectiveFormatter(matplotlib.ticker.FixedFormatter(['a','b']),
....: skip_values=[0,2])
sage: [formatter(i,1) for i in range(10)]
['', 'b', '', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
"""
if x in self.skip_values:
return ''
else:
return self.formatter(x, *args, **kwds)
return _SelectiveFormatterClass(formatter, skip_values)
def xydata_from_point_list(points):
r"""
Return two lists (xdata, ydata), each coerced to a list of floats,
which correspond to the x-coordinates and the y-coordinates of the
points.
The points parameter can be a list of 2-tuples or some object that
yields a list of one or two numbers.
This function can potentially be very slow for large point sets.
TESTS::
sage: from sage.plot.plot import xydata_from_point_list
sage: xydata_from_point_list([CC(0), CC(1)]) # issue 8082
([0.0, 1.0], [0.0, 0.0])
This function should work for anything than can be turned into a
list, such as iterators and such (see :issue:`10478`)::
sage: xydata_from_point_list(iter([(0,0), (sqrt(3), 2)]))
([0.0, 1.7320508075688772], [0.0, 2.0])
sage: xydata_from_point_list((x, x^2) for x in range(5))
([0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 4.0, 9.0, 16.0])
sage: xydata_from_point_list(enumerate(prime_range(1, 15)))
([0.0, 1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 5.0, 7.0, 11.0, 13.0])
sage: from builtins import zip
sage: xydata_from_point_list(list(zip([2,3,5,7], [11, 13, 17, 19])))
([2.0, 3.0, 5.0, 7.0], [11.0, 13.0, 17.0, 19.0])
The code now accepts mixed lists of complex and real numbers::
sage: xydata_from_point_list(map(N,[0,1,1+I,I,I-1,-1,-1-I,-I,1-I]))
([0.0, 1.0, 1.0, 0.0, -1.0, -1.0, -1.0, 0.0, 1.0],
[0.0, 0.0, 1.0, 1.0, 1.0, 0.0, -1.0, -1.0, -1.0])
sage: point2d([0, 1., CC(0,1)])
Graphics object consisting of 1 graphics primitive
sage: point2d((x^5-1).roots(multiplicities=False))
Graphics object consisting of 1 graphics primitive
"""
import numbers
zero = float(0)
xdata = []
ydata = []
for xy in points:
if isinstance(xy, Expression):
xy = xy.n()
if isinstance(xy, numbers.Real):
xdata.append(float(xy))
ydata.append(zero)
elif isinstance(xy, numbers.Complex):
xdata.append(float(xy.real()))
ydata.append(float(xy.imag()))
else:
try:
x, y = xy
except TypeError:
raise TypeError('invalid input for 2D point')
else:
xdata.append(float(x))
ydata.append(float(y))
return xdata, ydata
@options(alpha=1, thickness=1, fill=False, fillcolor='automatic',
fillalpha=0.5, plot_points=200, adaptive_tolerance=0.01,
adaptive_recursion=5, detect_poles=False, exclude=None,
legend_label=None, __original_opts=True,
aspect_ratio='automatic', imaginary_tolerance=1e-8)
def plot(funcs, *args, **kwds):
r"""
Use plot by writing.
``plot(X, ...)``
where `X` is a Sage object (or list of Sage objects) that
either is callable and returns numbers that can be coerced to
floats, or has a plot method that returns a
``GraphicPrimitive`` object.
There are many other specialized 2D plot commands available
in Sage, such as ``plot_slope_field``, as well as various
graphics primitives like :class:`~sage.plot.arrow.Arrow`;
type ``sage.plot.plot?`` for a current list.
Type ``plot.options`` for a dictionary of the default
options for plots. You can change this to change the defaults for
all future plots. Use ``plot.reset()`` to reset to the
default options.
PLOT OPTIONS:
- ``plot_points`` -- (default: 200) the minimal number of plot points
- ``adaptive_recursion`` -- (default: 5) how many levels of recursion to go
before giving up when doing adaptive refinement. Setting this to 0
disables adaptive refinement.
- ``adaptive_tolerance`` -- (default: 0.01) how large a difference should be
before the adaptive refinement code considers it significant. See the
documentation further below for more information, starting at "the
algorithm used to insert".
- ``imaginary_tolerance`` -- (default: ``1e-8``) if an imaginary
number arises (due, for example, to numerical issues), this
tolerance specifies how large it has to be in magnitude before
we raise an error. In other words, imaginary parts smaller than
this are ignored in your plot points.
- ``base`` -- (default: `10`) the base of the logarithm if
a logarithmic scale is set. This must be greater than 1. The base
can be also given as a list or tuple ``(basex, basey)``.
``basex`` sets the base of the logarithm along the horizontal
axis and ``basey`` sets the base along the vertical axis.
- ``scale`` -- string (default: ``'linear'``); scale of the axes.
Possible values are ``'linear'``, ``'loglog'``, ``'semilogx'``,
``'semilogy'``.
The scale can be also be given as single argument that is a list
or tuple ``(scale, base)`` or ``(scale, basex, basey)``.
The ``'loglog'`` scale sets both the horizontal and vertical axes to
logarithmic scale. The ``'semilogx'`` scale sets the horizontal axis
to logarithmic scale. The ``'semilogy'`` scale sets the vertical axis
to logarithmic scale. The ``'linear'`` scale is the default value
when :class:`~sage.plot.graphics.Graphics` is initialized.
- ``xmin`` -- starting x value in the rendered figure. This parameter is
passed directly to the ``show`` procedure and it could be overwritten.
- ``xmax`` -- ending x value in the rendered figure. This parameter is passed
directly to the ``show`` procedure and it could be overwritten.
- ``ymin`` -- starting y value in the rendered figure. This parameter is
passed directly to the ``show`` procedure and it could be overwritten.
- ``ymax`` -- ending y value in the rendered figure. This parameter is passed
directly to the ``show`` procedure and it could be overwritten.
- ``detect_poles`` -- boolean (default: ``False``); if set to ``True`` poles are detected.
If set to "show" vertical asymptotes are drawn.
- ``legend_label`` -- a (TeX) string serving as the label for `X` in the legend.
If `X` is a list, then this option can be a single string, or a list or dictionary
with strings as entries/values. If a dictionary, then keys are taken from ``range(len(X))``.
.. NOTE::
- If the ``scale`` is ``'linear'``, then irrespective of what
``base`` is set to, it will default to 10 and will remain unused.
- If you want to limit the plot along the horizontal axis in the
final rendered figure, then pass the ``xmin`` and ``xmax``
keywords to the :meth:`~sage.plot.graphics.Graphics.show` method.
To limit the plot along the vertical axis, ``ymin`` and ``ymax``
keywords can be provided to either this ``plot`` command or to
the ``show`` command.
- This function does NOT simply sample equally spaced points
between xmin and xmax. Instead it computes equally spaced points
and adds small perturbations to them. This reduces the possibility
of, e.g., sampling `\sin` only at multiples of `2\pi`, which would
yield a very misleading graph.
- If there is a range of consecutive points where the function has
no value, then those points will be excluded from the plot. See
the example below on automatic exclusion of points.
- For the other keyword options that the ``plot`` function can
take, refer to the method :meth:`~sage.plot.graphics.Graphics.show`
and the further options below.
COLOR OPTIONS:
- ``color`` -- (default: ``'blue'``) one of:
- an RGB tuple (r,g,b) with each of r,g,b between 0 and 1.
- a color name as a string (e.g., ``'purple'``).
- an HTML color such as '#aaff0b'.
- a list or dictionary of colors (valid only if `X` is a list):
if a dictionary, keys are taken from ``range(len(X))``;
the entries/values of the list/dictionary may be any of the options above.
- ``'automatic'`` -- maps to default ('blue') if `X` is a single Sage object; and
maps to a fixed sequence of regularly spaced colors if `X` is a list
- ``legend_color`` -- the color of the text for `X` (or each item in `X`) in the legend.
Default color is 'black'. Options are as in ``color`` above, except that the choice 'automatic' maps to 'black' if `X` is a single Sage object
- ``fillcolor`` -- the color of the fill for the plot of `X` (or each item in `X`).
Default color is 'gray' if `X` is a single Sage object or if ``color`` is a single color. Otherwise, options are as in ``color`` above
APPEARANCE OPTIONS:
The following options affect the appearance of
the line through the points on the graph of `X` (these are
the same as for the line function):
INPUT:
- ``alpha`` -- how transparent the line is
- ``thickness`` -- how thick the line is
- ``rgbcolor`` -- the color as an RGB tuple
- ``hue`` -- the color given as a hue
LINE OPTIONS:
Any MATPLOTLIB line option may also be passed in. E.g.,
- ``linestyle`` -- (default: ``'-'``) the style of the line, which is one of
- ``'-'`` or ``'solid'``
- ``'--'`` or ``'dashed'``
- ``'-.'`` or ``'dash dot'``
- ``':'`` or ``'dotted'``
- ``"None"`` or ``" "`` or ``""`` (nothing)