-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
plot.py
1234 lines (932 loc) · 39.8 KB
/
plot.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
"""Plotting module for SymPy.
A plot is represented by the ``Plot`` class that contains a reference to the
backend and a list of the data series to be plotted. The data series are
instances of classes meant to simplify getting points and meshes from SymPy
expressions. ``plot_backends`` is a dictionary with all the backends.
This module gives only the essential. For all the fancy stuff use directly
the backend. You can get the backend wrapper for every plot from the
``_backend`` attribute. Moreover the data series classes have various useful
methods like ``get_points``, ``get_meshes``, etc, that may
be useful if you wish to use another plotting library.
Especially if you need publication ready graphs and this module is not enough
for you - just get the ``_backend`` attribute and add whatever you want
directly to it. In the case of matplotlib (the common way to graph data in
python) just copy ``_backend.fig`` which is the figure and ``_backend.ax``
which is the axis and work on them as you would on any other matplotlib object.
Simplicity of code takes much greater importance than performance. Do not use it
if you care at all about performance. A new backend instance is initialized
every time you call ``show()`` and the old one is left to the garbage collector.
"""
from sympy.concrete.summations import Sum
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import Function, AppliedUndef
from sympy.core.symbol import (Dummy, Symbol, Wild)
from sympy.external import import_module
from sympy.functions import sign
from sympy.plotting.backends.base_backend import Plot
from sympy.plotting.backends.matplotlibbackend import MatplotlibBackend
from sympy.plotting.backends.textbackend import TextBackend
from sympy.plotting.series import (
LineOver1DRangeSeries, Parametric2DLineSeries, Parametric3DLineSeries,
ParametricSurfaceSeries, SurfaceOver2DRangeSeries, ContourSeries)
from sympy.plotting.utils import _check_arguments, _plot_sympify
from sympy.tensor.indexed import Indexed
# to maintain back-compatibility
from sympy.plotting.plotgrid import PlotGrid # noqa: F401
from sympy.plotting.series import BaseSeries # noqa: F401
from sympy.plotting.series import Line2DBaseSeries # noqa: F401
from sympy.plotting.series import Line3DBaseSeries # noqa: F401
from sympy.plotting.series import SurfaceBaseSeries # noqa: F401
from sympy.plotting.series import List2DSeries # noqa: F401
from sympy.plotting.series import GenericDataSeries # noqa: F401
from sympy.plotting.series import centers_of_faces # noqa: F401
from sympy.plotting.series import centers_of_segments # noqa: F401
from sympy.plotting.series import flat # noqa: F401
from sympy.plotting.backends.base_backend import unset_show # noqa: F401
from sympy.plotting.backends.matplotlibbackend import _matplotlib_list # noqa: F401
from sympy.plotting.textplot import textplot # noqa: F401
__doctest_requires__ = {
('plot3d',
'plot3d_parametric_line',
'plot3d_parametric_surface',
'plot_parametric'): ['matplotlib'],
# XXX: The plot doctest possibly should not require matplotlib. It fails at
# plot(x**2, (x, -5, 5)) which should be fine for text backend.
('plot',): ['matplotlib'],
}
def _process_summations(sum_bound, *args):
"""Substitute oo (infinity) in the lower/upper bounds of a summation with
some integer number.
Parameters
==========
sum_bound : int
oo will be substituted with this integer number.
*args : list/tuple
pre-processed arguments of the form (expr, range, ...)
Notes
=====
Let's consider the following summation: ``Sum(1 / x**2, (x, 1, oo))``.
The current implementation of lambdify (SymPy 1.12 at the time of
writing this) will create something of this form:
``sum(1 / x**2 for x in range(1, INF))``
The problem is that ``type(INF)`` is float, while ``range`` requires
integers: the evaluation fails.
Instead of modifying ``lambdify`` (which requires a deep knowledge), just
replace it with some integer number.
"""
def new_bound(t, bound):
if (not t.is_number) or t.is_finite:
return t
if sign(t) >= 0:
return bound
return -bound
args = list(args)
expr = args[0]
# select summations whose lower/upper bound is infinity
w = Wild("w", properties=[
lambda t: isinstance(t, Sum),
lambda t: any((not a[1].is_finite) or (not a[2].is_finite) for i, a in enumerate(t.args) if i > 0)
])
for t in list(expr.find(w)):
sums_args = list(t.args)
for i, a in enumerate(sums_args):
if i > 0:
sums_args[i] = (a[0], new_bound(a[1], sum_bound),
new_bound(a[2], sum_bound))
s = Sum(*sums_args)
expr = expr.subs(t, s)
args[0] = expr
return args
def _build_line_series(*args, **kwargs):
"""Loop over the provided arguments and create the necessary line series.
"""
series = []
sum_bound = int(kwargs.get("sum_bound", 1000))
for arg in args:
expr, r, label, rendering_kw = arg
kw = kwargs.copy()
if rendering_kw is not None:
kw["rendering_kw"] = rendering_kw
# TODO: _process_piecewise check goes here
if not callable(expr):
arg = _process_summations(sum_bound, *arg)
series.append(LineOver1DRangeSeries(*arg[:-1], **kw))
return series
def _create_series(series_type, plot_expr, **kwargs):
"""Extract the rendering_kw dictionary from the provided arguments and
create an appropriate data series.
"""
series = []
for args in plot_expr:
kw = kwargs.copy()
if args[-1] is not None:
kw["rendering_kw"] = args[-1]
series.append(series_type(*args[:-1], **kw))
return series
def _set_labels(series, labels, rendering_kw):
"""Apply the `label` and `rendering_kw` keyword arguments to the series.
"""
if not isinstance(labels, (list, tuple)):
labels = [labels]
if len(labels) > 0:
if len(labels) == 1 and len(series) > 1:
# if one label is provided and multiple series are being plotted,
# set the same label to all data series. It maintains
# back-compatibility
labels *= len(series)
if len(series) != len(labels):
raise ValueError("The number of labels must be equal to the "
"number of expressions being plotted.\nReceived "
f"{len(series)} expressions and {len(labels)} labels")
for s, l in zip(series, labels):
s.label = l
if rendering_kw:
if isinstance(rendering_kw, dict):
rendering_kw = [rendering_kw]
if len(rendering_kw) == 1:
rendering_kw *= len(series)
elif len(series) != len(rendering_kw):
raise ValueError("The number of rendering dictionaries must be "
"equal to the number of expressions being plotted.\nReceived "
f"{len(series)} expressions and {len(labels)} labels")
for s, r in zip(series, rendering_kw):
s.rendering_kw = r
def plot_factory(*args, **kwargs):
backend = kwargs.pop("backend", "default")
if isinstance(backend, str):
if backend == "default":
matplotlib = import_module('matplotlib',
min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
return MatplotlibBackend(*args, **kwargs)
return TextBackend(*args, **kwargs)
return plot_backends[backend](*args, **kwargs)
elif (type(backend) == type) and issubclass(backend, Plot):
return backend(*args, **kwargs)
else:
raise TypeError("backend must be either a string or a subclass of ``Plot``.")
plot_backends = {
'matplotlib': MatplotlibBackend,
'text': TextBackend,
}
####New API for plotting module ####
# TODO: Add color arrays for plots.
# TODO: Add more plotting options for 3d plots.
# TODO: Adaptive sampling for 3D plots.
def plot(*args, show=True, **kwargs):
"""Plots a function of a single variable as a curve.
Parameters
==========
args :
The first argument is the expression representing the function
of single variable to be plotted.
The last argument is a 3-tuple denoting the range of the free
variable. e.g. ``(x, 0, 5)``
Typical usage examples are in the following:
- Plotting a single expression with a single range.
``plot(expr, range, **kwargs)``
- Plotting a single expression with the default range (-10, 10).
``plot(expr, **kwargs)``
- Plotting multiple expressions with a single range.
``plot(expr1, expr2, ..., range, **kwargs)``
- Plotting multiple expressions with multiple ranges.
``plot((expr1, range1), (expr2, range2), ..., **kwargs)``
It is best practice to specify range explicitly because default
range may change in the future if a more advanced default range
detection algorithm is implemented.
show : bool, optional
The default value is set to ``True``. Set show to ``False`` and
the function will not display the plot. The returned instance of
the ``Plot`` class can then be used to save or display the plot
by calling the ``save()`` and ``show()`` methods respectively.
line_color : string, or float, or function, optional
Specifies the color for the plot.
See ``Plot`` to see how to set color for the plots.
Note that by setting ``line_color``, it would be applied simultaneously
to all the series.
title : str, optional
Title of the plot. It is set to the latex representation of
the expression, if the plot has only one expression.
label : str, optional
The label of the expression in the plot. It will be used when
called with ``legend``. Default is the name of the expression.
e.g. ``sin(x)``
xlabel : str or expression, optional
Label for the x-axis.
ylabel : str or expression, optional
Label for the y-axis.
xscale : 'linear' or 'log', optional
Sets the scaling of the x-axis.
yscale : 'linear' or 'log', optional
Sets the scaling of the y-axis.
axis_center : (float, float), optional
Tuple of two floats denoting the coordinates of the center or
{'center', 'auto'}
xlim : (float, float), optional
Denotes the x-axis limits, ``(min, max)```.
ylim : (float, float), optional
Denotes the y-axis limits, ``(min, max)```.
annotations : list, optional
A list of dictionaries specifying the type of annotation
required. The keys in the dictionary should be equivalent
to the arguments of the :external:mod:`matplotlib`'s
:external:meth:`~matplotlib.axes.Axes.annotate` method.
markers : list, optional
A list of dictionaries specifying the type the markers required.
The keys in the dictionary should be equivalent to the arguments
of the :external:mod:`matplotlib`'s :external:func:`~matplotlib.pyplot.plot()` function
along with the marker related keyworded arguments.
rectangles : list, optional
A list of dictionaries specifying the dimensions of the
rectangles to be plotted. The keys in the dictionary should be
equivalent to the arguments of the :external:mod:`matplotlib`'s
:external:class:`~matplotlib.patches.Rectangle` class.
fill : dict, optional
A dictionary specifying the type of color filling required in
the plot. The keys in the dictionary should be equivalent to the
arguments of the :external:mod:`matplotlib`'s
:external:meth:`~matplotlib.axes.Axes.fill_between` method.
adaptive : bool, optional
The default value is set to ``True``. Set adaptive to ``False``
and specify ``n`` if uniform sampling is required.
The plotting uses an adaptive algorithm which samples
recursively to accurately plot. The adaptive algorithm uses a
random point near the midpoint of two points that has to be
further sampled. Hence the same plots can appear slightly
different.
depth : int, optional
Recursion depth of the adaptive algorithm. A depth of value
`n` samples a maximum of `2^{n}` points.
If the ``adaptive`` flag is set to ``False``, this will be
ignored.
n : int, optional
Used when the ``adaptive`` is set to ``False``. The function
is uniformly sampled at ``n`` number of points. If the ``adaptive``
flag is set to ``True``, this will be ignored.
This keyword argument replaces ``nb_of_points``, which should be
considered deprecated.
size : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of
the overall figure. The default value is set to ``None``, meaning
the size will be set by the default backend.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.plotting import plot
>>> x = symbols('x')
Single Plot
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot(x**2, (x, -5, 5))
Plot object containing:
[0]: cartesian line: x**2 for x over (-5.0, 5.0)
Multiple plots with single range.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot(x, x**2, x**3, (x, -5, 5))
Plot object containing:
[0]: cartesian line: x for x over (-5.0, 5.0)
[1]: cartesian line: x**2 for x over (-5.0, 5.0)
[2]: cartesian line: x**3 for x over (-5.0, 5.0)
Multiple plots with different ranges.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
Plot object containing:
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
[1]: cartesian line: x for x over (-5.0, 5.0)
No adaptive sampling.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot(x**2, adaptive=False, n=400)
Plot object containing:
[0]: cartesian line: x**2 for x over (-10.0, 10.0)
See Also
========
Plot, LineOver1DRangeSeries
"""
args = _plot_sympify(args)
plot_expr = _check_arguments(args, 1, 1, **kwargs)
params = kwargs.get("params", None)
free = set()
for p in plot_expr:
if not isinstance(p[1][0], str):
free |= {p[1][0]}
else:
free |= {Symbol(p[1][0])}
if params:
free = free.difference(params.keys())
x = free.pop() if free else Symbol("x")
kwargs.setdefault('xlabel', x)
kwargs.setdefault('ylabel', Function('f')(x))
labels = kwargs.pop("label", [])
rendering_kw = kwargs.pop("rendering_kw", None)
series = _build_line_series(*plot_expr, **kwargs)
_set_labels(series, labels, rendering_kw)
plots = plot_factory(*series, **kwargs)
if show:
plots.show()
return plots
def plot_parametric(*args, show=True, **kwargs):
"""
Plots a 2D parametric curve.
Parameters
==========
args
Common specifications are:
- Plotting a single parametric curve with a range
``plot_parametric((expr_x, expr_y), range)``
- Plotting multiple parametric curves with the same range
``plot_parametric((expr_x, expr_y), ..., range)``
- Plotting multiple parametric curves with different ranges
``plot_parametric((expr_x, expr_y, range), ...)``
``expr_x`` is the expression representing $x$ component of the
parametric function.
``expr_y`` is the expression representing $y$ component of the
parametric function.
``range`` is a 3-tuple denoting the parameter symbol, start and
stop. For example, ``(u, 0, 5)``.
If the range is not specified, then a default range of (-10, 10)
is used.
However, if the arguments are specified as
``(expr_x, expr_y, range), ...``, you must specify the ranges
for each expressions manually.
Default range may change in the future if a more advanced
algorithm is implemented.
adaptive : bool, optional
Specifies whether to use the adaptive sampling or not.
The default value is set to ``True``. Set adaptive to ``False``
and specify ``n`` if uniform sampling is required.
depth : int, optional
The recursion depth of the adaptive algorithm. A depth of
value $n$ samples a maximum of $2^n$ points.
n : int, optional
Used when the ``adaptive`` flag is set to ``False``. Specifies the
number of the points used for the uniform sampling.
This keyword argument replaces ``nb_of_points``, which should be
considered deprecated.
line_color : string, or float, or function, optional
Specifies the color for the plot.
See ``Plot`` to see how to set color for the plots.
Note that by setting ``line_color``, it would be applied simultaneously
to all the series.
label : str, optional
The label of the expression in the plot. It will be used when
called with ``legend``. Default is the name of the expression.
e.g. ``sin(x)``
xlabel : str, optional
Label for the x-axis.
ylabel : str, optional
Label for the y-axis.
xscale : 'linear' or 'log', optional
Sets the scaling of the x-axis.
yscale : 'linear' or 'log', optional
Sets the scaling of the y-axis.
axis_center : (float, float), optional
Tuple of two floats denoting the coordinates of the center or
{'center', 'auto'}
xlim : (float, float), optional
Denotes the x-axis limits, ``(min, max)```.
ylim : (float, float), optional
Denotes the y-axis limits, ``(min, max)```.
size : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of
the overall figure. The default value is set to ``None``, meaning
the size will be set by the default backend.
Examples
========
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import plot_parametric, symbols, cos, sin
>>> u = symbols('u')
A parametric plot with a single expression:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot_parametric((cos(u), sin(u)), (u, -5, 5))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
A parametric plot with multiple expressions with the same range:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0)
[1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0)
A parametric plot with multiple expressions with different ranges
for each curve:
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot_parametric((cos(u), sin(u), (u, -5, 5)),
... (cos(u), u, (u, -5, 5)))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
[1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0)
Notes
=====
The plotting uses an adaptive algorithm which samples recursively to
accurately plot the curve. The adaptive algorithm uses a random point
near the midpoint of two points that has to be further sampled.
Hence, repeating the same plot command can give slightly different
results because of the random sampling.
If there are multiple plots, then the same optional arguments are
applied to all the plots drawn in the same canvas. If you want to
set these options separately, you can index the returned ``Plot``
object and set it.
For example, when you specify ``line_color`` once, it would be
applied simultaneously to both series.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import pi
>>> expr1 = (u, cos(2*pi*u)/2 + 1/2)
>>> expr2 = (u, sin(2*pi*u)/2 + 1/2)
>>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue')
If you want to specify the line color for the specific series, you
should index each item and apply the property manually.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> p[0].line_color = 'red'
>>> p.show()
See Also
========
Plot, Parametric2DLineSeries
"""
args = _plot_sympify(args)
plot_expr = _check_arguments(args, 2, 1, **kwargs)
labels = kwargs.pop("label", [])
rendering_kw = kwargs.pop("rendering_kw", None)
series = _create_series(Parametric2DLineSeries, plot_expr, **kwargs)
_set_labels(series, labels, rendering_kw)
plots = plot_factory(*series, **kwargs)
if show:
plots.show()
return plots
def plot3d_parametric_line(*args, show=True, **kwargs):
"""
Plots a 3D parametric line plot.
Usage
=====
Single plot:
``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)``
If the range is not specified, then a default range of (-10, 10) is used.
Multiple plots.
``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)``
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range
detection algorithm is implemented.
Arguments
=========
expr_x : Expression representing the function along x.
expr_y : Expression representing the function along y.
expr_z : Expression representing the function along z.
range : (:class:`~.Symbol`, float, float)
A 3-tuple denoting the range of the parameter variable, e.g., (u, 0, 5).
Keyword Arguments
=================
Arguments for ``Parametric3DLineSeries`` class.
n : int
The range is uniformly sampled at ``n`` number of points.
This keyword argument replaces ``nb_of_points``, which should be
considered deprecated.
Aesthetics:
line_color : string, or float, or function, optional
Specifies the color for the plot.
See ``Plot`` to see how to set color for the plots.
Note that by setting ``line_color``, it would be applied simultaneously
to all the series.
label : str
The label to the plot. It will be used when called with ``legend=True``
to denote the function with the given label in the plot.
If there are multiple plots, then the same series arguments are applied to
all the plots. If you want to set these options separately, you can index
the returned ``Plot`` object and set it.
Arguments for ``Plot`` class.
title : str
Title of the plot.
size : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of
the overall figure. The default value is set to ``None``, meaning
the size will be set by the default backend.
Examples
========
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import symbols, cos, sin
>>> from sympy.plotting import plot3d_parametric_line
>>> u = symbols('u')
Single plot.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5))
Plot object containing:
[0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
Multiple plots.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)),
... (sin(u), u**2, u, (u, -5, 5)))
Plot object containing:
[0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
[1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0)
See Also
========
Plot, Parametric3DLineSeries
"""
args = _plot_sympify(args)
plot_expr = _check_arguments(args, 3, 1, **kwargs)
kwargs.setdefault("xlabel", "x")
kwargs.setdefault("ylabel", "y")
kwargs.setdefault("zlabel", "z")
labels = kwargs.pop("label", [])
rendering_kw = kwargs.pop("rendering_kw", None)
series = _create_series(Parametric3DLineSeries, plot_expr, **kwargs)
_set_labels(series, labels, rendering_kw)
plots = plot_factory(*series, **kwargs)
if show:
plots.show()
return plots
def _plot3d_plot_contour_helper(Series, *args, **kwargs):
"""plot3d and plot_contour are structurally identical. Let's reduce
code repetition.
"""
# NOTE: if this import would be at the top-module level, it would trigger
# SymPy's optional-dependencies tests to fail.
from sympy.vector import BaseScalar
args = _plot_sympify(args)
plot_expr = _check_arguments(args, 1, 2, **kwargs)
free_x = set()
free_y = set()
_types = (Symbol, BaseScalar, Indexed, AppliedUndef)
for p in plot_expr:
free_x |= {p[1][0]} if isinstance(p[1][0], _types) else {Symbol(p[1][0])}
free_y |= {p[2][0]} if isinstance(p[2][0], _types) else {Symbol(p[2][0])}
x = free_x.pop() if free_x else Symbol("x")
y = free_y.pop() if free_y else Symbol("y")
kwargs.setdefault("xlabel", x)
kwargs.setdefault("ylabel", y)
kwargs.setdefault("zlabel", Function('f')(x, y))
# if a polar discretization is requested and automatic labelling has ben
# applied, hide the labels on the x-y axis.
if kwargs.get("is_polar", False):
if callable(kwargs["xlabel"]):
kwargs["xlabel"] = ""
if callable(kwargs["ylabel"]):
kwargs["ylabel"] = ""
labels = kwargs.pop("label", [])
rendering_kw = kwargs.pop("rendering_kw", None)
series = _create_series(Series, plot_expr, **kwargs)
_set_labels(series, labels, rendering_kw)
plots = plot_factory(*series, **kwargs)
if kwargs.get("show", True):
plots.show()
return plots
def plot3d(*args, show=True, **kwargs):
"""
Plots a 3D surface plot.
Usage
=====
Single plot
``plot3d(expr, range_x, range_y, **kwargs)``
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plot with the same range.
``plot3d(expr1, expr2, range_x, range_y, **kwargs)``
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plots with different ranges.
``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range
detection algorithm is implemented.
Arguments
=========
expr : Expression representing the function along x.
range_x : (:class:`~.Symbol`, float, float)
A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
range_y : (:class:`~.Symbol`, float, float)
A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
Keyword Arguments
=================
Arguments for ``SurfaceOver2DRangeSeries`` class:
n1 : int
The x range is sampled uniformly at ``n1`` of points.
This keyword argument replaces ``nb_of_points_x``, which should be
considered deprecated.
n2 : int
The y range is sampled uniformly at ``n2`` of points.
This keyword argument replaces ``nb_of_points_y``, which should be
considered deprecated.
Aesthetics:
surface_color : Function which returns a float
Specifies the color for the surface of the plot.
See :class:`~.Plot` for more details.
If there are multiple plots, then the same series arguments are applied to
all the plots. If you want to set these options separately, you can index
the returned ``Plot`` object and set it.
Arguments for ``Plot`` class:
title : str
Title of the plot.
size : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of the
overall figure. The default value is set to ``None``, meaning the size will
be set by the default backend.
Examples
========
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.plotting import plot3d
>>> x, y = symbols('x y')
Single plot
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d(x*y, (x, -5, 5), (y, -5, 5))
Plot object containing:
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
Multiple plots with same range
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
Plot object containing:
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
[1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
Multiple plots with different ranges.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)),
... (x*y, (x, -3, 3), (y, -3, 3)))
Plot object containing:
[0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0)
[1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0)
See Also
========
Plot, SurfaceOver2DRangeSeries
"""
kwargs.setdefault("show", show)
return _plot3d_plot_contour_helper(
SurfaceOver2DRangeSeries, *args, **kwargs)
def plot3d_parametric_surface(*args, show=True, **kwargs):
"""
Plots a 3D parametric surface plot.
Explanation
===========
Single plot.
``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)``
If the ranges is not specified, then a default range of (-10, 10) is used.
Multiple plots.
``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)``
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range
detection algorithm is implemented.
Arguments
=========
expr_x : Expression representing the function along ``x``.
expr_y : Expression representing the function along ``y``.
expr_z : Expression representing the function along ``z``.
range_u : (:class:`~.Symbol`, float, float)
A 3-tuple denoting the range of the u variable, e.g. (u, 0, 5).
range_v : (:class:`~.Symbol`, float, float)
A 3-tuple denoting the range of the v variable, e.g. (v, 0, 5).
Keyword Arguments
=================
Arguments for ``ParametricSurfaceSeries`` class:
n1 : int
The ``u`` range is sampled uniformly at ``n1`` of points.
This keyword argument replaces ``nb_of_points_u``, which should be
considered deprecated.
n2 : int
The ``v`` range is sampled uniformly at ``n2`` of points.
This keyword argument replaces ``nb_of_points_v``, which should be
considered deprecated.
Aesthetics:
surface_color : Function which returns a float
Specifies the color for the surface of the plot. See
:class:`~Plot` for more details.
If there are multiple plots, then the same series arguments are applied for
all the plots. If you want to set these options separately, you can index
the returned ``Plot`` object and set it.
Arguments for ``Plot`` class:
title : str
Title of the plot.
size : (float, float), optional
A tuple in the form (width, height) in inches to specify the size of the
overall figure. The default value is set to ``None``, meaning the size will
be set by the default backend.
Examples
========