plot.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637
  1. """Plotting module for SymPy.
  2. A plot is represented by the ``Plot`` class that contains a reference to the
  3. backend and a list of the data series to be plotted. The data series are
  4. instances of classes meant to simplify getting points and meshes from SymPy
  5. expressions. ``plot_backends`` is a dictionary with all the backends.
  6. This module gives only the essential. For all the fancy stuff use directly
  7. the backend. You can get the backend wrapper for every plot from the
  8. ``_backend`` attribute. Moreover the data series classes have various useful
  9. methods like ``get_points``, ``get_meshes``, etc, that may
  10. be useful if you wish to use another plotting library.
  11. Especially if you need publication ready graphs and this module is not enough
  12. for you - just get the ``_backend`` attribute and add whatever you want
  13. directly to it. In the case of matplotlib (the common way to graph data in
  14. python) just copy ``_backend.fig`` which is the figure and ``_backend.ax``
  15. which is the axis and work on them as you would on any other matplotlib object.
  16. Simplicity of code takes much greater importance than performance. Do not use it
  17. if you care at all about performance. A new backend instance is initialized
  18. every time you call ``show()`` and the old one is left to the garbage collector.
  19. """
  20. from collections.abc import Callable
  21. from sympy.core.basic import Basic
  22. from sympy.core.containers import Tuple
  23. from sympy.core.expr import Expr
  24. from sympy.core.function import arity, Function
  25. from sympy.core.symbol import (Dummy, Symbol)
  26. from sympy.core.sympify import sympify
  27. from sympy.external import import_module
  28. from sympy.printing.latex import latex
  29. from sympy.utilities.exceptions import sympy_deprecation_warning
  30. from sympy.utilities.iterables import is_sequence
  31. from .experimental_lambdify import (vectorized_lambdify, lambdify)
  32. # N.B.
  33. # When changing the minimum module version for matplotlib, please change
  34. # the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py`
  35. # Backend specific imports - textplot
  36. from sympy.plotting.textplot import textplot
  37. # Global variable
  38. # Set to False when running tests / doctests so that the plots don't show.
  39. _show = True
  40. def unset_show():
  41. """
  42. Disable show(). For use in the tests.
  43. """
  44. global _show
  45. _show = False
  46. def _str_or_latex(label):
  47. if isinstance(label, Basic):
  48. return latex(label, mode='inline')
  49. return str(label)
  50. ##############################################################################
  51. # The public interface
  52. ##############################################################################
  53. class Plot:
  54. """The central class of the plotting module.
  55. Explanation
  56. ===========
  57. For interactive work the function :func:`plot()` is better suited.
  58. This class permits the plotting of SymPy expressions using numerous
  59. backends (:external:mod:`matplotlib`, textplot, the old pyglet module for SymPy, Google
  60. charts api, etc).
  61. The figure can contain an arbitrary number of plots of SymPy expressions,
  62. lists of coordinates of points, etc. Plot has a private attribute _series that
  63. contains all data series to be plotted (expressions for lines or surfaces,
  64. lists of points, etc (all subclasses of BaseSeries)). Those data series are
  65. instances of classes not imported by ``from sympy import *``.
  66. The customization of the figure is on two levels. Global options that
  67. concern the figure as a whole (e.g. title, xlabel, scale, etc) and
  68. per-data series options (e.g. name) and aesthetics (e.g. color, point shape,
  69. line type, etc.).
  70. The difference between options and aesthetics is that an aesthetic can be
  71. a function of the coordinates (or parameters in a parametric plot). The
  72. supported values for an aesthetic are:
  73. - None (the backend uses default values)
  74. - a constant
  75. - a function of one variable (the first coordinate or parameter)
  76. - a function of two variables (the first and second coordinate or parameters)
  77. - a function of three variables (only in nonparametric 3D plots)
  78. Their implementation depends on the backend so they may not work in some
  79. backends.
  80. If the plot is parametric and the arity of the aesthetic function permits
  81. it the aesthetic is calculated over parameters and not over coordinates.
  82. If the arity does not permit calculation over parameters the calculation is
  83. done over coordinates.
  84. Only cartesian coordinates are supported for the moment, but you can use
  85. the parametric plots to plot in polar, spherical and cylindrical
  86. coordinates.
  87. The arguments for the constructor Plot must be subclasses of BaseSeries.
  88. Any global option can be specified as a keyword argument.
  89. The global options for a figure are:
  90. - title : str
  91. - xlabel : str or Symbol
  92. - ylabel : str or Symbol
  93. - zlabel : str or Symbol
  94. - legend : bool
  95. - xscale : {'linear', 'log'}
  96. - yscale : {'linear', 'log'}
  97. - axis : bool
  98. - axis_center : tuple of two floats or {'center', 'auto'}
  99. - xlim : tuple of two floats
  100. - ylim : tuple of two floats
  101. - aspect_ratio : tuple of two floats or {'auto'}
  102. - autoscale : bool
  103. - margin : float in [0, 1]
  104. - backend : {'default', 'matplotlib', 'text'} or a subclass of BaseBackend
  105. - size : optional tuple of two floats, (width, height); default: None
  106. The per data series options and aesthetics are:
  107. There are none in the base series. See below for options for subclasses.
  108. Some data series support additional aesthetics or options:
  109. :class:`~.LineOver1DRangeSeries`, :class:`~.Parametric2DLineSeries`, and
  110. :class:`~.Parametric3DLineSeries` support the following:
  111. Aesthetics:
  112. - line_color : string, or float, or function, optional
  113. Specifies the color for the plot, which depends on the backend being
  114. used.
  115. For example, if ``MatplotlibBackend`` is being used, then
  116. Matplotlib string colors are acceptable (``"red"``, ``"r"``,
  117. ``"cyan"``, ``"c"``, ...).
  118. Alternatively, we can use a float number, 0 < color < 1, wrapped in a
  119. string (for example, ``line_color="0.5"``) to specify grayscale colors.
  120. Alternatively, We can specify a function returning a single
  121. float value: this will be used to apply a color-loop (for example,
  122. ``line_color=lambda x: math.cos(x)``).
  123. Note that by setting line_color, it would be applied simultaneously
  124. to all the series.
  125. Options:
  126. - label : str
  127. - steps : bool
  128. - integers_only : bool
  129. :class:`~.SurfaceOver2DRangeSeries` and :class:`~.ParametricSurfaceSeries`
  130. support the following:
  131. Aesthetics:
  132. - surface_color : function which returns a float.
  133. """
  134. def __init__(self, *args,
  135. title=None, xlabel=None, ylabel=None, zlabel=None, aspect_ratio='auto',
  136. xlim=None, ylim=None, axis_center='auto', axis=True,
  137. xscale='linear', yscale='linear', legend=False, autoscale=True,
  138. margin=0, annotations=None, markers=None, rectangles=None,
  139. fill=None, backend='default', size=None, **kwargs):
  140. super().__init__()
  141. # Options for the graph as a whole.
  142. # The possible values for each option are described in the docstring of
  143. # Plot. They are based purely on convention, no checking is done.
  144. self.title = title
  145. self.xlabel = xlabel
  146. self.ylabel = ylabel
  147. self.zlabel = zlabel
  148. self.aspect_ratio = aspect_ratio
  149. self.axis_center = axis_center
  150. self.axis = axis
  151. self.xscale = xscale
  152. self.yscale = yscale
  153. self.legend = legend
  154. self.autoscale = autoscale
  155. self.margin = margin
  156. self.annotations = annotations
  157. self.markers = markers
  158. self.rectangles = rectangles
  159. self.fill = fill
  160. # Contains the data objects to be plotted. The backend should be smart
  161. # enough to iterate over this list.
  162. self._series = []
  163. self._series.extend(args)
  164. # The backend type. On every show() a new backend instance is created
  165. # in self._backend which is tightly coupled to the Plot instance
  166. # (thanks to the parent attribute of the backend).
  167. if isinstance(backend, str):
  168. self.backend = plot_backends[backend]
  169. elif (type(backend) == type) and issubclass(backend, BaseBackend):
  170. self.backend = backend
  171. else:
  172. raise TypeError(
  173. "backend must be either a string or a subclass of BaseBackend")
  174. is_real = \
  175. lambda lim: all(getattr(i, 'is_real', True) for i in lim)
  176. is_finite = \
  177. lambda lim: all(getattr(i, 'is_finite', True) for i in lim)
  178. # reduce code repetition
  179. def check_and_set(t_name, t):
  180. if t:
  181. if not is_real(t):
  182. raise ValueError(
  183. "All numbers from {}={} must be real".format(t_name, t))
  184. if not is_finite(t):
  185. raise ValueError(
  186. "All numbers from {}={} must be finite".format(t_name, t))
  187. setattr(self, t_name, (float(t[0]), float(t[1])))
  188. self.xlim = None
  189. check_and_set("xlim", xlim)
  190. self.ylim = None
  191. check_and_set("ylim", ylim)
  192. self.size = None
  193. check_and_set("size", size)
  194. def show(self):
  195. # TODO move this to the backend (also for save)
  196. if hasattr(self, '_backend'):
  197. self._backend.close()
  198. self._backend = self.backend(self)
  199. self._backend.show()
  200. def save(self, path):
  201. if hasattr(self, '_backend'):
  202. self._backend.close()
  203. self._backend = self.backend(self)
  204. self._backend.save(path)
  205. def __str__(self):
  206. series_strs = [('[%d]: ' % i) + str(s)
  207. for i, s in enumerate(self._series)]
  208. return 'Plot object containing:\n' + '\n'.join(series_strs)
  209. def __getitem__(self, index):
  210. return self._series[index]
  211. def __setitem__(self, index, *args):
  212. if len(args) == 1 and isinstance(args[0], BaseSeries):
  213. self._series[index] = args
  214. def __delitem__(self, index):
  215. del self._series[index]
  216. def append(self, arg):
  217. """Adds an element from a plot's series to an existing plot.
  218. Examples
  219. ========
  220. Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
  221. second plot's first series object to the first, use the
  222. ``append`` method, like so:
  223. .. plot::
  224. :format: doctest
  225. :include-source: True
  226. >>> from sympy import symbols
  227. >>> from sympy.plotting import plot
  228. >>> x = symbols('x')
  229. >>> p1 = plot(x*x, show=False)
  230. >>> p2 = plot(x, show=False)
  231. >>> p1.append(p2[0])
  232. >>> p1
  233. Plot object containing:
  234. [0]: cartesian line: x**2 for x over (-10.0, 10.0)
  235. [1]: cartesian line: x for x over (-10.0, 10.0)
  236. >>> p1.show()
  237. See Also
  238. ========
  239. extend
  240. """
  241. if isinstance(arg, BaseSeries):
  242. self._series.append(arg)
  243. else:
  244. raise TypeError('Must specify element of plot to append.')
  245. def extend(self, arg):
  246. """Adds all series from another plot.
  247. Examples
  248. ========
  249. Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
  250. second plot to the first, use the ``extend`` method, like so:
  251. .. plot::
  252. :format: doctest
  253. :include-source: True
  254. >>> from sympy import symbols
  255. >>> from sympy.plotting import plot
  256. >>> x = symbols('x')
  257. >>> p1 = plot(x**2, show=False)
  258. >>> p2 = plot(x, -x, show=False)
  259. >>> p1.extend(p2)
  260. >>> p1
  261. Plot object containing:
  262. [0]: cartesian line: x**2 for x over (-10.0, 10.0)
  263. [1]: cartesian line: x for x over (-10.0, 10.0)
  264. [2]: cartesian line: -x for x over (-10.0, 10.0)
  265. >>> p1.show()
  266. """
  267. if isinstance(arg, Plot):
  268. self._series.extend(arg._series)
  269. elif is_sequence(arg):
  270. self._series.extend(arg)
  271. else:
  272. raise TypeError('Expecting Plot or sequence of BaseSeries')
  273. class PlotGrid:
  274. """This class helps to plot subplots from already created SymPy plots
  275. in a single figure.
  276. Examples
  277. ========
  278. .. plot::
  279. :context: close-figs
  280. :format: doctest
  281. :include-source: True
  282. >>> from sympy import symbols
  283. >>> from sympy.plotting import plot, plot3d, PlotGrid
  284. >>> x, y = symbols('x, y')
  285. >>> p1 = plot(x, x**2, x**3, (x, -5, 5))
  286. >>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
  287. >>> p3 = plot(x**3, (x, -5, 5))
  288. >>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))
  289. Plotting vertically in a single line:
  290. .. plot::
  291. :context: close-figs
  292. :format: doctest
  293. :include-source: True
  294. >>> PlotGrid(2, 1, p1, p2)
  295. PlotGrid object containing:
  296. Plot[0]:Plot object containing:
  297. [0]: cartesian line: x for x over (-5.0, 5.0)
  298. [1]: cartesian line: x**2 for x over (-5.0, 5.0)
  299. [2]: cartesian line: x**3 for x over (-5.0, 5.0)
  300. Plot[1]:Plot object containing:
  301. [0]: cartesian line: x**2 for x over (-6.0, 6.0)
  302. [1]: cartesian line: x for x over (-5.0, 5.0)
  303. Plotting horizontally in a single line:
  304. .. plot::
  305. :context: close-figs
  306. :format: doctest
  307. :include-source: True
  308. >>> PlotGrid(1, 3, p2, p3, p4)
  309. PlotGrid object containing:
  310. Plot[0]:Plot object containing:
  311. [0]: cartesian line: x**2 for x over (-6.0, 6.0)
  312. [1]: cartesian line: x for x over (-5.0, 5.0)
  313. Plot[1]:Plot object containing:
  314. [0]: cartesian line: x**3 for x over (-5.0, 5.0)
  315. Plot[2]:Plot object containing:
  316. [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
  317. Plotting in a grid form:
  318. .. plot::
  319. :context: close-figs
  320. :format: doctest
  321. :include-source: True
  322. >>> PlotGrid(2, 2, p1, p2, p3, p4)
  323. PlotGrid object containing:
  324. Plot[0]:Plot object containing:
  325. [0]: cartesian line: x for x over (-5.0, 5.0)
  326. [1]: cartesian line: x**2 for x over (-5.0, 5.0)
  327. [2]: cartesian line: x**3 for x over (-5.0, 5.0)
  328. Plot[1]:Plot object containing:
  329. [0]: cartesian line: x**2 for x over (-6.0, 6.0)
  330. [1]: cartesian line: x for x over (-5.0, 5.0)
  331. Plot[2]:Plot object containing:
  332. [0]: cartesian line: x**3 for x over (-5.0, 5.0)
  333. Plot[3]:Plot object containing:
  334. [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
  335. """
  336. def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs):
  337. """
  338. Parameters
  339. ==========
  340. nrows :
  341. The number of rows that should be in the grid of the
  342. required subplot.
  343. ncolumns :
  344. The number of columns that should be in the grid
  345. of the required subplot.
  346. nrows and ncolumns together define the required grid.
  347. Arguments
  348. =========
  349. A list of predefined plot objects entered in a row-wise sequence
  350. i.e. plot objects which are to be in the top row of the required
  351. grid are written first, then the second row objects and so on
  352. Keyword arguments
  353. =================
  354. show : Boolean
  355. The default value is set to ``True``. Set show to ``False`` and
  356. the function will not display the subplot. The returned instance
  357. of the ``PlotGrid`` class can then be used to save or display the
  358. plot by calling the ``save()`` and ``show()`` methods
  359. respectively.
  360. size : (float, float), optional
  361. A tuple in the form (width, height) in inches to specify the size of
  362. the overall figure. The default value is set to ``None``, meaning
  363. the size will be set by the default backend.
  364. """
  365. self.nrows = nrows
  366. self.ncolumns = ncolumns
  367. self._series = []
  368. self.args = args
  369. for arg in args:
  370. self._series.append(arg._series)
  371. self.backend = DefaultBackend
  372. self.size = size
  373. if show:
  374. self.show()
  375. def show(self):
  376. if hasattr(self, '_backend'):
  377. self._backend.close()
  378. self._backend = self.backend(self)
  379. self._backend.show()
  380. def save(self, path):
  381. if hasattr(self, '_backend'):
  382. self._backend.close()
  383. self._backend = self.backend(self)
  384. self._backend.save(path)
  385. def __str__(self):
  386. plot_strs = [('Plot[%d]:' % i) + str(plot)
  387. for i, plot in enumerate(self.args)]
  388. return 'PlotGrid object containing:\n' + '\n'.join(plot_strs)
  389. ##############################################################################
  390. # Data Series
  391. ##############################################################################
  392. #TODO more general way to calculate aesthetics (see get_color_array)
  393. ### The base class for all series
  394. class BaseSeries:
  395. """Base class for the data objects containing stuff to be plotted.
  396. Explanation
  397. ===========
  398. The backend should check if it supports the data series that is given.
  399. (e.g. TextBackend supports only LineOver1DRangeSeries).
  400. It is the backend responsibility to know how to use the class of
  401. data series that is given.
  402. Some data series classes are grouped (using a class attribute like is_2Dline)
  403. according to the api they present (based only on convention). The backend is
  404. not obliged to use that api (e.g. LineOver1DRangeSeries belongs to the
  405. is_2Dline group and presents the get_points method, but the
  406. TextBackend does not use the get_points method).
  407. """
  408. # Some flags follow. The rationale for using flags instead of checking base
  409. # classes is that setting multiple flags is simpler than multiple
  410. # inheritance.
  411. is_2Dline = False
  412. # Some of the backends expect:
  413. # - get_points returning 1D np.arrays list_x, list_y
  414. # - get_color_array returning 1D np.array (done in Line2DBaseSeries)
  415. # with the colors calculated at the points from get_points
  416. is_3Dline = False
  417. # Some of the backends expect:
  418. # - get_points returning 1D np.arrays list_x, list_y, list_y
  419. # - get_color_array returning 1D np.array (done in Line2DBaseSeries)
  420. # with the colors calculated at the points from get_points
  421. is_3Dsurface = False
  422. # Some of the backends expect:
  423. # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
  424. # - get_points an alias for get_meshes
  425. is_contour = False
  426. # Some of the backends expect:
  427. # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
  428. # - get_points an alias for get_meshes
  429. is_implicit = False
  430. # Some of the backends expect:
  431. # - get_meshes returning mesh_x (1D array), mesh_y(1D array,
  432. # mesh_z (2D np.arrays)
  433. # - get_points an alias for get_meshes
  434. # Different from is_contour as the colormap in backend will be
  435. # different
  436. is_parametric = False
  437. # The calculation of aesthetics expects:
  438. # - get_parameter_points returning one or two np.arrays (1D or 2D)
  439. # used for calculation aesthetics
  440. def __init__(self):
  441. super().__init__()
  442. @property
  443. def is_3D(self):
  444. flags3D = [
  445. self.is_3Dline,
  446. self.is_3Dsurface
  447. ]
  448. return any(flags3D)
  449. @property
  450. def is_line(self):
  451. flagslines = [
  452. self.is_2Dline,
  453. self.is_3Dline
  454. ]
  455. return any(flagslines)
  456. ### 2D lines
  457. class Line2DBaseSeries(BaseSeries):
  458. """A base class for 2D lines.
  459. - adding the label, steps and only_integers options
  460. - making is_2Dline true
  461. - defining get_segments and get_color_array
  462. """
  463. is_2Dline = True
  464. _dim = 2
  465. def __init__(self):
  466. super().__init__()
  467. self.label = None
  468. self.steps = False
  469. self.only_integers = False
  470. self.line_color = None
  471. def get_data(self):
  472. """ Return lists of coordinates for plotting the line.
  473. Returns
  474. =======
  475. x : list
  476. List of x-coordinates
  477. y : list
  478. List of y-coordinates
  479. z : list
  480. List of z-coordinates in case of Parametric3DLineSeries
  481. """
  482. np = import_module('numpy')
  483. points = self.get_points()
  484. if self.steps is True:
  485. if len(points) == 2:
  486. x = np.array((points[0], points[0])).T.flatten()[1:]
  487. y = np.array((points[1], points[1])).T.flatten()[:-1]
  488. points = (x, y)
  489. else:
  490. x = np.repeat(points[0], 3)[2:]
  491. y = np.repeat(points[1], 3)[:-2]
  492. z = np.repeat(points[2], 3)[1:-1]
  493. points = (x, y, z)
  494. return points
  495. def get_segments(self):
  496. sympy_deprecation_warning(
  497. """
  498. The Line2DBaseSeries.get_segments() method is deprecated.
  499. Instead, use the MatplotlibBackend.get_segments() method, or use
  500. The get_points() or get_data() methods.
  501. """,
  502. deprecated_since_version="1.9",
  503. active_deprecations_target="deprecated-get-segments")
  504. np = import_module('numpy')
  505. points = type(self).get_data(self)
  506. points = np.ma.array(points).T.reshape(-1, 1, self._dim)
  507. return np.ma.concatenate([points[:-1], points[1:]], axis=1)
  508. def get_color_array(self):
  509. np = import_module('numpy')
  510. c = self.line_color
  511. if hasattr(c, '__call__'):
  512. f = np.vectorize(c)
  513. nargs = arity(c)
  514. if nargs == 1 and self.is_parametric:
  515. x = self.get_parameter_points()
  516. return f(centers_of_segments(x))
  517. else:
  518. variables = list(map(centers_of_segments, self.get_points()))
  519. if nargs == 1:
  520. return f(variables[0])
  521. elif nargs == 2:
  522. return f(*variables[:2])
  523. else: # only if the line is 3D (otherwise raises an error)
  524. return f(*variables)
  525. else:
  526. return c*np.ones(self.nb_of_points)
  527. class List2DSeries(Line2DBaseSeries):
  528. """Representation for a line consisting of list of points."""
  529. def __init__(self, list_x, list_y):
  530. np = import_module('numpy')
  531. super().__init__()
  532. self.list_x = np.array(list_x)
  533. self.list_y = np.array(list_y)
  534. self.label = 'list'
  535. def __str__(self):
  536. return 'list plot'
  537. def get_points(self):
  538. return (self.list_x, self.list_y)
  539. class LineOver1DRangeSeries(Line2DBaseSeries):
  540. """Representation for a line consisting of a SymPy expression over a range."""
  541. def __init__(self, expr, var_start_end, **kwargs):
  542. super().__init__()
  543. self.expr = sympify(expr)
  544. self.label = kwargs.get('label', None) or self.expr
  545. self.var = sympify(var_start_end[0])
  546. self.start = float(var_start_end[1])
  547. self.end = float(var_start_end[2])
  548. self.nb_of_points = kwargs.get('nb_of_points', 300)
  549. self.adaptive = kwargs.get('adaptive', True)
  550. self.depth = kwargs.get('depth', 12)
  551. self.line_color = kwargs.get('line_color', None)
  552. self.xscale = kwargs.get('xscale', 'linear')
  553. def __str__(self):
  554. return 'cartesian line: %s for %s over %s' % (
  555. str(self.expr), str(self.var), str((self.start, self.end)))
  556. def get_points(self):
  557. """ Return lists of coordinates for plotting. Depending on the
  558. ``adaptive`` option, this function will either use an adaptive algorithm
  559. or it will uniformly sample the expression over the provided range.
  560. Returns
  561. =======
  562. x : list
  563. List of x-coordinates
  564. y : list
  565. List of y-coordinates
  566. Explanation
  567. ===========
  568. The adaptive sampling is done by recursively checking if three
  569. points are almost collinear. If they are not collinear, then more
  570. points are added between those points.
  571. References
  572. ==========
  573. .. [1] Adaptive polygonal approximation of parametric curves,
  574. Luiz Henrique de Figueiredo.
  575. """
  576. if self.only_integers or not self.adaptive:
  577. return self._uniform_sampling()
  578. else:
  579. f = lambdify([self.var], self.expr)
  580. x_coords = []
  581. y_coords = []
  582. np = import_module('numpy')
  583. def sample(p, q, depth):
  584. """ Samples recursively if three points are almost collinear.
  585. For depth < 6, points are added irrespective of whether they
  586. satisfy the collinearity condition or not. The maximum depth
  587. allowed is 12.
  588. """
  589. # Randomly sample to avoid aliasing.
  590. random = 0.45 + np.random.rand() * 0.1
  591. if self.xscale == 'log':
  592. xnew = 10**(np.log10(p[0]) + random * (np.log10(q[0]) -
  593. np.log10(p[0])))
  594. else:
  595. xnew = p[0] + random * (q[0] - p[0])
  596. ynew = f(xnew)
  597. new_point = np.array([xnew, ynew])
  598. # Maximum depth
  599. if depth > self.depth:
  600. x_coords.append(q[0])
  601. y_coords.append(q[1])
  602. # Sample irrespective of whether the line is flat till the
  603. # depth of 6. We are not using linspace to avoid aliasing.
  604. elif depth < 6:
  605. sample(p, new_point, depth + 1)
  606. sample(new_point, q, depth + 1)
  607. # Sample ten points if complex values are encountered
  608. # at both ends. If there is a real value in between, then
  609. # sample those points further.
  610. elif p[1] is None and q[1] is None:
  611. if self.xscale == 'log':
  612. xarray = np.logspace(p[0], q[0], 10)
  613. else:
  614. xarray = np.linspace(p[0], q[0], 10)
  615. yarray = list(map(f, xarray))
  616. if not all(y is None for y in yarray):
  617. for i in range(len(yarray) - 1):
  618. if not (yarray[i] is None and yarray[i + 1] is None):
  619. sample([xarray[i], yarray[i]],
  620. [xarray[i + 1], yarray[i + 1]], depth + 1)
  621. # Sample further if one of the end points in None (i.e. a
  622. # complex value) or the three points are not almost collinear.
  623. elif (p[1] is None or q[1] is None or new_point[1] is None
  624. or not flat(p, new_point, q)):
  625. sample(p, new_point, depth + 1)
  626. sample(new_point, q, depth + 1)
  627. else:
  628. x_coords.append(q[0])
  629. y_coords.append(q[1])
  630. f_start = f(self.start)
  631. f_end = f(self.end)
  632. x_coords.append(self.start)
  633. y_coords.append(f_start)
  634. sample(np.array([self.start, f_start]),
  635. np.array([self.end, f_end]), 0)
  636. return (x_coords, y_coords)
  637. def _uniform_sampling(self):
  638. np = import_module('numpy')
  639. if self.only_integers is True:
  640. if self.xscale == 'log':
  641. list_x = np.logspace(int(self.start), int(self.end),
  642. num=int(self.end) - int(self.start) + 1)
  643. else:
  644. list_x = np.linspace(int(self.start), int(self.end),
  645. num=int(self.end) - int(self.start) + 1)
  646. else:
  647. if self.xscale == 'log':
  648. list_x = np.logspace(self.start, self.end, num=self.nb_of_points)
  649. else:
  650. list_x = np.linspace(self.start, self.end, num=self.nb_of_points)
  651. f = vectorized_lambdify([self.var], self.expr)
  652. list_y = f(list_x)
  653. return (list_x, list_y)
  654. class Parametric2DLineSeries(Line2DBaseSeries):
  655. """Representation for a line consisting of two parametric SymPy expressions
  656. over a range."""
  657. is_parametric = True
  658. def __init__(self, expr_x, expr_y, var_start_end, **kwargs):
  659. super().__init__()
  660. self.expr_x = sympify(expr_x)
  661. self.expr_y = sympify(expr_y)
  662. self.label = kwargs.get('label', None) or \
  663. Tuple(self.expr_x, self.expr_y)
  664. self.var = sympify(var_start_end[0])
  665. self.start = float(var_start_end[1])
  666. self.end = float(var_start_end[2])
  667. self.nb_of_points = kwargs.get('nb_of_points', 300)
  668. self.adaptive = kwargs.get('adaptive', True)
  669. self.depth = kwargs.get('depth', 12)
  670. self.line_color = kwargs.get('line_color', None)
  671. def __str__(self):
  672. return 'parametric cartesian line: (%s, %s) for %s over %s' % (
  673. str(self.expr_x), str(self.expr_y), str(self.var),
  674. str((self.start, self.end)))
  675. def get_parameter_points(self):
  676. np = import_module('numpy')
  677. return np.linspace(self.start, self.end, num=self.nb_of_points)
  678. def _uniform_sampling(self):
  679. param = self.get_parameter_points()
  680. fx = vectorized_lambdify([self.var], self.expr_x)
  681. fy = vectorized_lambdify([self.var], self.expr_y)
  682. list_x = fx(param)
  683. list_y = fy(param)
  684. return (list_x, list_y)
  685. def get_points(self):
  686. """ Return lists of coordinates for plotting. Depending on the
  687. ``adaptive`` option, this function will either use an adaptive algorithm
  688. or it will uniformly sample the expression over the provided range.
  689. Returns
  690. =======
  691. x : list
  692. List of x-coordinates
  693. y : list
  694. List of y-coordinates
  695. Explanation
  696. ===========
  697. The adaptive sampling is done by recursively checking if three
  698. points are almost collinear. If they are not collinear, then more
  699. points are added between those points.
  700. References
  701. ==========
  702. .. [1] Adaptive polygonal approximation of parametric curves,
  703. Luiz Henrique de Figueiredo.
  704. """
  705. if not self.adaptive:
  706. return self._uniform_sampling()
  707. f_x = lambdify([self.var], self.expr_x)
  708. f_y = lambdify([self.var], self.expr_y)
  709. x_coords = []
  710. y_coords = []
  711. def sample(param_p, param_q, p, q, depth):
  712. """ Samples recursively if three points are almost collinear.
  713. For depth < 6, points are added irrespective of whether they
  714. satisfy the collinearity condition or not. The maximum depth
  715. allowed is 12.
  716. """
  717. # Randomly sample to avoid aliasing.
  718. np = import_module('numpy')
  719. random = 0.45 + np.random.rand() * 0.1
  720. param_new = param_p + random * (param_q - param_p)
  721. xnew = f_x(param_new)
  722. ynew = f_y(param_new)
  723. new_point = np.array([xnew, ynew])
  724. # Maximum depth
  725. if depth > self.depth:
  726. x_coords.append(q[0])
  727. y_coords.append(q[1])
  728. # Sample irrespective of whether the line is flat till the
  729. # depth of 6. We are not using linspace to avoid aliasing.
  730. elif depth < 6:
  731. sample(param_p, param_new, p, new_point, depth + 1)
  732. sample(param_new, param_q, new_point, q, depth + 1)
  733. # Sample ten points if complex values are encountered
  734. # at both ends. If there is a real value in between, then
  735. # sample those points further.
  736. elif ((p[0] is None and q[1] is None) or
  737. (p[1] is None and q[1] is None)):
  738. param_array = np.linspace(param_p, param_q, 10)
  739. x_array = list(map(f_x, param_array))
  740. y_array = list(map(f_y, param_array))
  741. if not all(x is None and y is None
  742. for x, y in zip(x_array, y_array)):
  743. for i in range(len(y_array) - 1):
  744. if ((x_array[i] is not None and y_array[i] is not None) or
  745. (x_array[i + 1] is not None and y_array[i + 1] is not None)):
  746. point_a = [x_array[i], y_array[i]]
  747. point_b = [x_array[i + 1], y_array[i + 1]]
  748. sample(param_array[i], param_array[i], point_a,
  749. point_b, depth + 1)
  750. # Sample further if one of the end points in None (i.e. a complex
  751. # value) or the three points are not almost collinear.
  752. elif (p[0] is None or p[1] is None
  753. or q[1] is None or q[0] is None
  754. or not flat(p, new_point, q)):
  755. sample(param_p, param_new, p, new_point, depth + 1)
  756. sample(param_new, param_q, new_point, q, depth + 1)
  757. else:
  758. x_coords.append(q[0])
  759. y_coords.append(q[1])
  760. f_start_x = f_x(self.start)
  761. f_start_y = f_y(self.start)
  762. start = [f_start_x, f_start_y]
  763. f_end_x = f_x(self.end)
  764. f_end_y = f_y(self.end)
  765. end = [f_end_x, f_end_y]
  766. x_coords.append(f_start_x)
  767. y_coords.append(f_start_y)
  768. sample(self.start, self.end, start, end, 0)
  769. return x_coords, y_coords
  770. ### 3D lines
  771. class Line3DBaseSeries(Line2DBaseSeries):
  772. """A base class for 3D lines.
  773. Most of the stuff is derived from Line2DBaseSeries."""
  774. is_2Dline = False
  775. is_3Dline = True
  776. _dim = 3
  777. def __init__(self):
  778. super().__init__()
  779. class Parametric3DLineSeries(Line3DBaseSeries):
  780. """Representation for a 3D line consisting of three parametric SymPy
  781. expressions and a range."""
  782. is_parametric = True
  783. def __init__(self, expr_x, expr_y, expr_z, var_start_end, **kwargs):
  784. super().__init__()
  785. self.expr_x = sympify(expr_x)
  786. self.expr_y = sympify(expr_y)
  787. self.expr_z = sympify(expr_z)
  788. self.label = kwargs.get('label', None) or \
  789. Tuple(self.expr_x, self.expr_y)
  790. self.var = sympify(var_start_end[0])
  791. self.start = float(var_start_end[1])
  792. self.end = float(var_start_end[2])
  793. self.nb_of_points = kwargs.get('nb_of_points', 300)
  794. self.line_color = kwargs.get('line_color', None)
  795. self._xlim = None
  796. self._ylim = None
  797. self._zlim = None
  798. def __str__(self):
  799. return '3D parametric cartesian line: (%s, %s, %s) for %s over %s' % (
  800. str(self.expr_x), str(self.expr_y), str(self.expr_z),
  801. str(self.var), str((self.start, self.end)))
  802. def get_parameter_points(self):
  803. np = import_module('numpy')
  804. return np.linspace(self.start, self.end, num=self.nb_of_points)
  805. def get_points(self):
  806. np = import_module('numpy')
  807. param = self.get_parameter_points()
  808. fx = vectorized_lambdify([self.var], self.expr_x)
  809. fy = vectorized_lambdify([self.var], self.expr_y)
  810. fz = vectorized_lambdify([self.var], self.expr_z)
  811. list_x = fx(param)
  812. list_y = fy(param)
  813. list_z = fz(param)
  814. list_x = np.array(list_x, dtype=np.float64)
  815. list_y = np.array(list_y, dtype=np.float64)
  816. list_z = np.array(list_z, dtype=np.float64)
  817. list_x = np.ma.masked_invalid(list_x)
  818. list_y = np.ma.masked_invalid(list_y)
  819. list_z = np.ma.masked_invalid(list_z)
  820. self._xlim = (np.amin(list_x), np.amax(list_x))
  821. self._ylim = (np.amin(list_y), np.amax(list_y))
  822. self._zlim = (np.amin(list_z), np.amax(list_z))
  823. return list_x, list_y, list_z
  824. ### Surfaces
  825. class SurfaceBaseSeries(BaseSeries):
  826. """A base class for 3D surfaces."""
  827. is_3Dsurface = True
  828. def __init__(self):
  829. super().__init__()
  830. self.surface_color = None
  831. def get_color_array(self):
  832. np = import_module('numpy')
  833. c = self.surface_color
  834. if isinstance(c, Callable):
  835. f = np.vectorize(c)
  836. nargs = arity(c)
  837. if self.is_parametric:
  838. variables = list(map(centers_of_faces, self.get_parameter_meshes()))
  839. if nargs == 1:
  840. return f(variables[0])
  841. elif nargs == 2:
  842. return f(*variables)
  843. variables = list(map(centers_of_faces, self.get_meshes()))
  844. if nargs == 1:
  845. return f(variables[0])
  846. elif nargs == 2:
  847. return f(*variables[:2])
  848. else:
  849. return f(*variables)
  850. else:
  851. if isinstance(self, SurfaceOver2DRangeSeries):
  852. return c*np.ones(min(self.nb_of_points_x, self.nb_of_points_y))
  853. else:
  854. return c*np.ones(min(self.nb_of_points_u, self.nb_of_points_v))
  855. class SurfaceOver2DRangeSeries(SurfaceBaseSeries):
  856. """Representation for a 3D surface consisting of a SymPy expression and 2D
  857. range."""
  858. def __init__(self, expr, var_start_end_x, var_start_end_y, **kwargs):
  859. super().__init__()
  860. self.expr = sympify(expr)
  861. self.var_x = sympify(var_start_end_x[0])
  862. self.start_x = float(var_start_end_x[1])
  863. self.end_x = float(var_start_end_x[2])
  864. self.var_y = sympify(var_start_end_y[0])
  865. self.start_y = float(var_start_end_y[1])
  866. self.end_y = float(var_start_end_y[2])
  867. self.nb_of_points_x = kwargs.get('nb_of_points_x', 50)
  868. self.nb_of_points_y = kwargs.get('nb_of_points_y', 50)
  869. self.surface_color = kwargs.get('surface_color', None)
  870. self._xlim = (self.start_x, self.end_x)
  871. self._ylim = (self.start_y, self.end_y)
  872. def __str__(self):
  873. return ('cartesian surface: %s for'
  874. ' %s over %s and %s over %s') % (
  875. str(self.expr),
  876. str(self.var_x),
  877. str((self.start_x, self.end_x)),
  878. str(self.var_y),
  879. str((self.start_y, self.end_y)))
  880. def get_meshes(self):
  881. np = import_module('numpy')
  882. mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x,
  883. num=self.nb_of_points_x),
  884. np.linspace(self.start_y, self.end_y,
  885. num=self.nb_of_points_y))
  886. f = vectorized_lambdify((self.var_x, self.var_y), self.expr)
  887. mesh_z = f(mesh_x, mesh_y)
  888. mesh_z = np.array(mesh_z, dtype=np.float64)
  889. mesh_z = np.ma.masked_invalid(mesh_z)
  890. self._zlim = (np.amin(mesh_z), np.amax(mesh_z))
  891. return mesh_x, mesh_y, mesh_z
  892. class ParametricSurfaceSeries(SurfaceBaseSeries):
  893. """Representation for a 3D surface consisting of three parametric SymPy
  894. expressions and a range."""
  895. is_parametric = True
  896. def __init__(
  897. self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v,
  898. **kwargs):
  899. super().__init__()
  900. self.expr_x = sympify(expr_x)
  901. self.expr_y = sympify(expr_y)
  902. self.expr_z = sympify(expr_z)
  903. self.var_u = sympify(var_start_end_u[0])
  904. self.start_u = float(var_start_end_u[1])
  905. self.end_u = float(var_start_end_u[2])
  906. self.var_v = sympify(var_start_end_v[0])
  907. self.start_v = float(var_start_end_v[1])
  908. self.end_v = float(var_start_end_v[2])
  909. self.nb_of_points_u = kwargs.get('nb_of_points_u', 50)
  910. self.nb_of_points_v = kwargs.get('nb_of_points_v', 50)
  911. self.surface_color = kwargs.get('surface_color', None)
  912. def __str__(self):
  913. return ('parametric cartesian surface: (%s, %s, %s) for'
  914. ' %s over %s and %s over %s') % (
  915. str(self.expr_x),
  916. str(self.expr_y),
  917. str(self.expr_z),
  918. str(self.var_u),
  919. str((self.start_u, self.end_u)),
  920. str(self.var_v),
  921. str((self.start_v, self.end_v)))
  922. def get_parameter_meshes(self):
  923. np = import_module('numpy')
  924. return np.meshgrid(np.linspace(self.start_u, self.end_u,
  925. num=self.nb_of_points_u),
  926. np.linspace(self.start_v, self.end_v,
  927. num=self.nb_of_points_v))
  928. def get_meshes(self):
  929. np = import_module('numpy')
  930. mesh_u, mesh_v = self.get_parameter_meshes()
  931. fx = vectorized_lambdify((self.var_u, self.var_v), self.expr_x)
  932. fy = vectorized_lambdify((self.var_u, self.var_v), self.expr_y)
  933. fz = vectorized_lambdify((self.var_u, self.var_v), self.expr_z)
  934. mesh_x = fx(mesh_u, mesh_v)
  935. mesh_y = fy(mesh_u, mesh_v)
  936. mesh_z = fz(mesh_u, mesh_v)
  937. mesh_x = np.array(mesh_x, dtype=np.float64)
  938. mesh_y = np.array(mesh_y, dtype=np.float64)
  939. mesh_z = np.array(mesh_z, dtype=np.float64)
  940. mesh_x = np.ma.masked_invalid(mesh_x)
  941. mesh_y = np.ma.masked_invalid(mesh_y)
  942. mesh_z = np.ma.masked_invalid(mesh_z)
  943. self._xlim = (np.amin(mesh_x), np.amax(mesh_x))
  944. self._ylim = (np.amin(mesh_y), np.amax(mesh_y))
  945. self._zlim = (np.amin(mesh_z), np.amax(mesh_z))
  946. return mesh_x, mesh_y, mesh_z
  947. ### Contours
  948. class ContourSeries(BaseSeries):
  949. """Representation for a contour plot."""
  950. # The code is mostly repetition of SurfaceOver2DRange.
  951. # Presently used in contour_plot function
  952. is_contour = True
  953. def __init__(self, expr, var_start_end_x, var_start_end_y):
  954. super().__init__()
  955. self.nb_of_points_x = 50
  956. self.nb_of_points_y = 50
  957. self.expr = sympify(expr)
  958. self.var_x = sympify(var_start_end_x[0])
  959. self.start_x = float(var_start_end_x[1])
  960. self.end_x = float(var_start_end_x[2])
  961. self.var_y = sympify(var_start_end_y[0])
  962. self.start_y = float(var_start_end_y[1])
  963. self.end_y = float(var_start_end_y[2])
  964. self.get_points = self.get_meshes
  965. self._xlim = (self.start_x, self.end_x)
  966. self._ylim = (self.start_y, self.end_y)
  967. def __str__(self):
  968. return ('contour: %s for '
  969. '%s over %s and %s over %s') % (
  970. str(self.expr),
  971. str(self.var_x),
  972. str((self.start_x, self.end_x)),
  973. str(self.var_y),
  974. str((self.start_y, self.end_y)))
  975. def get_meshes(self):
  976. np = import_module('numpy')
  977. mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x,
  978. num=self.nb_of_points_x),
  979. np.linspace(self.start_y, self.end_y,
  980. num=self.nb_of_points_y))
  981. f = vectorized_lambdify((self.var_x, self.var_y), self.expr)
  982. return (mesh_x, mesh_y, f(mesh_x, mesh_y))
  983. ##############################################################################
  984. # Backends
  985. ##############################################################################
  986. class BaseBackend:
  987. """Base class for all backends. A backend represents the plotting library,
  988. which implements the necessary functionalities in order to use SymPy
  989. plotting functions.
  990. How the plotting module works:
  991. 1. Whenever a plotting function is called, the provided expressions are
  992. processed and a list of instances of the :class:`BaseSeries` class is
  993. created, containing the necessary information to plot the expressions
  994. (e.g. the expression, ranges, series name, ...). Eventually, these
  995. objects will generate the numerical data to be plotted.
  996. 2. A :class:`~.Plot` object is instantiated, which stores the list of
  997. series and the main attributes of the plot (e.g. axis labels, title, ...).
  998. 3. When the ``show`` command is executed, a new backend is instantiated,
  999. which loops through each series object to generate and plot the
  1000. numerical data. The backend is also going to set the axis labels, title,
  1001. ..., according to the values stored in the Plot instance.
  1002. The backend should check if it supports the data series that it is given
  1003. (e.g. :class:`TextBackend` supports only :class:`LineOver1DRangeSeries`).
  1004. It is the backend responsibility to know how to use the class of data series
  1005. that it's given. Note that the current implementation of the ``*Series``
  1006. classes is "matplotlib-centric": the numerical data returned by the
  1007. ``get_points`` and ``get_meshes`` methods is meant to be used directly by
  1008. Matplotlib. Therefore, the new backend will have to pre-process the
  1009. numerical data to make it compatible with the chosen plotting library.
  1010. Keep in mind that future SymPy versions may improve the ``*Series`` classes
  1011. in order to return numerical data "non-matplotlib-centric", hence if you code
  1012. a new backend you have the responsibility to check if its working on each
  1013. SymPy release.
  1014. Please explore the :class:`MatplotlibBackend` source code to understand how a
  1015. backend should be coded.
  1016. Methods
  1017. =======
  1018. In order to be used by SymPy plotting functions, a backend must implement
  1019. the following methods:
  1020. * show(self): used to loop over the data series, generate the numerical
  1021. data, plot it and set the axis labels, title, ...
  1022. * save(self, path): used to save the current plot to the specified file
  1023. path.
  1024. * close(self): used to close the current plot backend (note: some plotting
  1025. library does not support this functionality. In that case, just raise a
  1026. warning).
  1027. See also
  1028. ========
  1029. MatplotlibBackend
  1030. """
  1031. def __init__(self, parent):
  1032. super().__init__()
  1033. self.parent = parent
  1034. def show(self):
  1035. raise NotImplementedError
  1036. def save(self, path):
  1037. raise NotImplementedError
  1038. def close(self):
  1039. raise NotImplementedError
  1040. # Don't have to check for the success of importing matplotlib in each case;
  1041. # we will only be using this backend if we can successfully import matploblib
  1042. class MatplotlibBackend(BaseBackend):
  1043. """ This class implements the functionalities to use Matplotlib with SymPy
  1044. plotting functions.
  1045. """
  1046. def __init__(self, parent):
  1047. super().__init__(parent)
  1048. self.matplotlib = import_module('matplotlib',
  1049. import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
  1050. min_module_version='1.1.0', catch=(RuntimeError,))
  1051. self.plt = self.matplotlib.pyplot
  1052. self.cm = self.matplotlib.cm
  1053. self.LineCollection = self.matplotlib.collections.LineCollection
  1054. aspect = getattr(self.parent, 'aspect_ratio', 'auto')
  1055. if aspect != 'auto':
  1056. aspect = float(aspect[1]) / aspect[0]
  1057. if isinstance(self.parent, Plot):
  1058. nrows, ncolumns = 1, 1
  1059. series_list = [self.parent._series]
  1060. elif isinstance(self.parent, PlotGrid):
  1061. nrows, ncolumns = self.parent.nrows, self.parent.ncolumns
  1062. series_list = self.parent._series
  1063. self.ax = []
  1064. self.fig = self.plt.figure(figsize=parent.size)
  1065. for i, series in enumerate(series_list):
  1066. are_3D = [s.is_3D for s in series]
  1067. if any(are_3D) and not all(are_3D):
  1068. raise ValueError('The matplotlib backend cannot mix 2D and 3D.')
  1069. elif all(are_3D):
  1070. # mpl_toolkits.mplot3d is necessary for
  1071. # projection='3d'
  1072. mpl_toolkits = import_module('mpl_toolkits', # noqa
  1073. import_kwargs={'fromlist': ['mplot3d']})
  1074. self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, projection='3d', aspect=aspect))
  1075. elif not any(are_3D):
  1076. self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, aspect=aspect))
  1077. self.ax[i].spines['left'].set_position('zero')
  1078. self.ax[i].spines['right'].set_color('none')
  1079. self.ax[i].spines['bottom'].set_position('zero')
  1080. self.ax[i].spines['top'].set_color('none')
  1081. self.ax[i].xaxis.set_ticks_position('bottom')
  1082. self.ax[i].yaxis.set_ticks_position('left')
  1083. @staticmethod
  1084. def get_segments(x, y, z=None):
  1085. """ Convert two list of coordinates to a list of segments to be used
  1086. with Matplotlib's :external:class:`~matplotlib.collections.LineCollection`.
  1087. Parameters
  1088. ==========
  1089. x : list
  1090. List of x-coordinates
  1091. y : list
  1092. List of y-coordinates
  1093. z : list
  1094. List of z-coordinates for a 3D line.
  1095. """
  1096. np = import_module('numpy')
  1097. if z is not None:
  1098. dim = 3
  1099. points = (x, y, z)
  1100. else:
  1101. dim = 2
  1102. points = (x, y)
  1103. points = np.ma.array(points).T.reshape(-1, 1, dim)
  1104. return np.ma.concatenate([points[:-1], points[1:]], axis=1)
  1105. def _process_series(self, series, ax, parent):
  1106. np = import_module('numpy')
  1107. mpl_toolkits = import_module(
  1108. 'mpl_toolkits', import_kwargs={'fromlist': ['mplot3d']})
  1109. # XXX Workaround for matplotlib issue
  1110. # https://github.com/matplotlib/matplotlib/issues/17130
  1111. xlims, ylims, zlims = [], [], []
  1112. for s in series:
  1113. # Create the collections
  1114. if s.is_2Dline:
  1115. x, y = s.get_data()
  1116. if (isinstance(s.line_color, (int, float)) or
  1117. callable(s.line_color)):
  1118. segments = self.get_segments(x, y)
  1119. collection = self.LineCollection(segments)
  1120. collection.set_array(s.get_color_array())
  1121. ax.add_collection(collection)
  1122. else:
  1123. lbl = _str_or_latex(s.label)
  1124. line, = ax.plot(x, y, label=lbl, color=s.line_color)
  1125. elif s.is_contour:
  1126. ax.contour(*s.get_meshes())
  1127. elif s.is_3Dline:
  1128. x, y, z = s.get_data()
  1129. if (isinstance(s.line_color, (int, float)) or
  1130. callable(s.line_color)):
  1131. art3d = mpl_toolkits.mplot3d.art3d
  1132. segments = self.get_segments(x, y, z)
  1133. collection = art3d.Line3DCollection(segments)
  1134. collection.set_array(s.get_color_array())
  1135. ax.add_collection(collection)
  1136. else:
  1137. lbl = _str_or_latex(s.label)
  1138. ax.plot(x, y, z, label=lbl, color=s.line_color)
  1139. xlims.append(s._xlim)
  1140. ylims.append(s._ylim)
  1141. zlims.append(s._zlim)
  1142. elif s.is_3Dsurface:
  1143. x, y, z = s.get_meshes()
  1144. collection = ax.plot_surface(x, y, z,
  1145. cmap=getattr(self.cm, 'viridis', self.cm.jet),
  1146. rstride=1, cstride=1, linewidth=0.1)
  1147. if isinstance(s.surface_color, (float, int, Callable)):
  1148. color_array = s.get_color_array()
  1149. color_array = color_array.reshape(color_array.size)
  1150. collection.set_array(color_array)
  1151. else:
  1152. collection.set_color(s.surface_color)
  1153. xlims.append(s._xlim)
  1154. ylims.append(s._ylim)
  1155. zlims.append(s._zlim)
  1156. elif s.is_implicit:
  1157. points = s.get_raster()
  1158. if len(points) == 2:
  1159. # interval math plotting
  1160. x, y = _matplotlib_list(points[0])
  1161. ax.fill(x, y, facecolor=s.line_color, edgecolor='None')
  1162. else:
  1163. # use contourf or contour depending on whether it is
  1164. # an inequality or equality.
  1165. # XXX: ``contour`` plots multiple lines. Should be fixed.
  1166. ListedColormap = self.matplotlib.colors.ListedColormap
  1167. colormap = ListedColormap(["white", s.line_color])
  1168. xarray, yarray, zarray, plot_type = points
  1169. if plot_type == 'contour':
  1170. ax.contour(xarray, yarray, zarray, cmap=colormap)
  1171. else:
  1172. ax.contourf(xarray, yarray, zarray, cmap=colormap)
  1173. else:
  1174. raise NotImplementedError(
  1175. '{} is not supported in the SymPy plotting module '
  1176. 'with matplotlib backend. Please report this issue.'
  1177. .format(ax))
  1178. Axes3D = mpl_toolkits.mplot3d.Axes3D
  1179. if not isinstance(ax, Axes3D):
  1180. ax.autoscale_view(
  1181. scalex=ax.get_autoscalex_on(),
  1182. scaley=ax.get_autoscaley_on())
  1183. else:
  1184. # XXX Workaround for matplotlib issue
  1185. # https://github.com/matplotlib/matplotlib/issues/17130
  1186. if xlims:
  1187. xlims = np.array(xlims)
  1188. xlim = (np.amin(xlims[:, 0]), np.amax(xlims[:, 1]))
  1189. ax.set_xlim(xlim)
  1190. else:
  1191. ax.set_xlim([0, 1])
  1192. if ylims:
  1193. ylims = np.array(ylims)
  1194. ylim = (np.amin(ylims[:, 0]), np.amax(ylims[:, 1]))
  1195. ax.set_ylim(ylim)
  1196. else:
  1197. ax.set_ylim([0, 1])
  1198. if zlims:
  1199. zlims = np.array(zlims)
  1200. zlim = (np.amin(zlims[:, 0]), np.amax(zlims[:, 1]))
  1201. ax.set_zlim(zlim)
  1202. else:
  1203. ax.set_zlim([0, 1])
  1204. # Set global options.
  1205. # TODO The 3D stuff
  1206. # XXX The order of those is important.
  1207. if parent.xscale and not isinstance(ax, Axes3D):
  1208. ax.set_xscale(parent.xscale)
  1209. if parent.yscale and not isinstance(ax, Axes3D):
  1210. ax.set_yscale(parent.yscale)
  1211. if not isinstance(ax, Axes3D) or self.matplotlib.__version__ >= '1.2.0': # XXX in the distant future remove this check
  1212. ax.set_autoscale_on(parent.autoscale)
  1213. if parent.axis_center:
  1214. val = parent.axis_center
  1215. if isinstance(ax, Axes3D):
  1216. pass
  1217. elif val == 'center':
  1218. ax.spines['left'].set_position('center')
  1219. ax.spines['bottom'].set_position('center')
  1220. elif val == 'auto':
  1221. xl, xh = ax.get_xlim()
  1222. yl, yh = ax.get_ylim()
  1223. pos_left = ('data', 0) if xl*xh <= 0 else 'center'
  1224. pos_bottom = ('data', 0) if yl*yh <= 0 else 'center'
  1225. ax.spines['left'].set_position(pos_left)
  1226. ax.spines['bottom'].set_position(pos_bottom)
  1227. else:
  1228. ax.spines['left'].set_position(('data', val[0]))
  1229. ax.spines['bottom'].set_position(('data', val[1]))
  1230. if not parent.axis:
  1231. ax.set_axis_off()
  1232. if parent.legend:
  1233. if ax.legend():
  1234. ax.legend_.set_visible(parent.legend)
  1235. if parent.margin:
  1236. ax.set_xmargin(parent.margin)
  1237. ax.set_ymargin(parent.margin)
  1238. if parent.title:
  1239. ax.set_title(parent.title)
  1240. if parent.xlabel:
  1241. xlbl = _str_or_latex(parent.xlabel)
  1242. ax.set_xlabel(xlbl, position=(1, 0))
  1243. if parent.ylabel:
  1244. ylbl = _str_or_latex(parent.ylabel)
  1245. ax.set_ylabel(ylbl, position=(0, 1))
  1246. if isinstance(ax, Axes3D) and parent.zlabel:
  1247. zlbl = _str_or_latex(parent.zlabel)
  1248. ax.set_zlabel(zlbl, position=(0, 1))
  1249. if parent.annotations:
  1250. for a in parent.annotations:
  1251. ax.annotate(**a)
  1252. if parent.markers:
  1253. for marker in parent.markers:
  1254. # make a copy of the marker dictionary
  1255. # so that it doesn't get altered
  1256. m = marker.copy()
  1257. args = m.pop('args')
  1258. ax.plot(*args, **m)
  1259. if parent.rectangles:
  1260. for r in parent.rectangles:
  1261. rect = self.matplotlib.patches.Rectangle(**r)
  1262. ax.add_patch(rect)
  1263. if parent.fill:
  1264. ax.fill_between(**parent.fill)
  1265. # xlim and ylim should always be set at last so that plot limits
  1266. # doesn't get altered during the process.
  1267. if parent.xlim:
  1268. ax.set_xlim(parent.xlim)
  1269. if parent.ylim:
  1270. ax.set_ylim(parent.ylim)
  1271. def process_series(self):
  1272. """
  1273. Iterates over every ``Plot`` object and further calls
  1274. _process_series()
  1275. """
  1276. parent = self.parent
  1277. if isinstance(parent, Plot):
  1278. series_list = [parent._series]
  1279. else:
  1280. series_list = parent._series
  1281. for i, (series, ax) in enumerate(zip(series_list, self.ax)):
  1282. if isinstance(self.parent, PlotGrid):
  1283. parent = self.parent.args[i]
  1284. self._process_series(series, ax, parent)
  1285. def show(self):
  1286. self.process_series()
  1287. #TODO after fixing https://github.com/ipython/ipython/issues/1255
  1288. # you can uncomment the next line and remove the pyplot.show() call
  1289. #self.fig.show()
  1290. if _show:
  1291. self.fig.tight_layout()
  1292. self.plt.show()
  1293. else:
  1294. self.close()
  1295. def save(self, path):
  1296. self.process_series()
  1297. self.fig.savefig(path)
  1298. def close(self):
  1299. self.plt.close(self.fig)
  1300. class TextBackend(BaseBackend):
  1301. def __init__(self, parent):
  1302. super().__init__(parent)
  1303. def show(self):
  1304. if not _show:
  1305. return
  1306. if len(self.parent._series) != 1:
  1307. raise ValueError(
  1308. 'The TextBackend supports only one graph per Plot.')
  1309. elif not isinstance(self.parent._series[0], LineOver1DRangeSeries):
  1310. raise ValueError(
  1311. 'The TextBackend supports only expressions over a 1D range')
  1312. else:
  1313. ser = self.parent._series[0]
  1314. textplot(ser.expr, ser.start, ser.end)
  1315. def close(self):
  1316. pass
  1317. class DefaultBackend(BaseBackend):
  1318. def __new__(cls, parent):
  1319. matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
  1320. if matplotlib:
  1321. return MatplotlibBackend(parent)
  1322. else:
  1323. return TextBackend(parent)
  1324. plot_backends = {
  1325. 'matplotlib': MatplotlibBackend,
  1326. 'text': TextBackend,
  1327. 'default': DefaultBackend
  1328. }
  1329. ##############################################################################
  1330. # Finding the centers of line segments or mesh faces
  1331. ##############################################################################
  1332. def centers_of_segments(array):
  1333. np = import_module('numpy')
  1334. return np.mean(np.vstack((array[:-1], array[1:])), 0)
  1335. def centers_of_faces(array):
  1336. np = import_module('numpy')
  1337. return np.mean(np.dstack((array[:-1, :-1],
  1338. array[1:, :-1],
  1339. array[:-1, 1:],
  1340. array[:-1, :-1],
  1341. )), 2)
  1342. def flat(x, y, z, eps=1e-3):
  1343. """Checks whether three points are almost collinear"""
  1344. np = import_module('numpy')
  1345. # Workaround plotting piecewise (#8577):
  1346. # workaround for `lambdify` in `.experimental_lambdify` fails
  1347. # to return numerical values in some cases. Lower-level fix
  1348. # in `lambdify` is possible.
  1349. vector_a = (x - y).astype(np.float64)
  1350. vector_b = (z - y).astype(np.float64)
  1351. dot_product = np.dot(vector_a, vector_b)
  1352. vector_a_norm = np.linalg.norm(vector_a)
  1353. vector_b_norm = np.linalg.norm(vector_b)
  1354. cos_theta = dot_product / (vector_a_norm * vector_b_norm)
  1355. return abs(cos_theta + 1) < eps
  1356. def _matplotlib_list(interval_list):
  1357. """
  1358. Returns lists for matplotlib ``fill`` command from a list of bounding
  1359. rectangular intervals
  1360. """
  1361. xlist = []
  1362. ylist = []
  1363. if len(interval_list):
  1364. for intervals in interval_list:
  1365. intervalx = intervals[0]
  1366. intervaly = intervals[1]
  1367. xlist.extend([intervalx.start, intervalx.start,
  1368. intervalx.end, intervalx.end, None])
  1369. ylist.extend([intervaly.start, intervaly.end,
  1370. intervaly.end, intervaly.start, None])
  1371. else:
  1372. #XXX Ugly hack. Matplotlib does not accept empty lists for ``fill``
  1373. xlist.extend((None, None, None, None))
  1374. ylist.extend((None, None, None, None))
  1375. return xlist, ylist
  1376. ####New API for plotting module ####
  1377. # TODO: Add color arrays for plots.
  1378. # TODO: Add more plotting options for 3d plots.
  1379. # TODO: Adaptive sampling for 3D plots.
  1380. def plot(*args, show=True, **kwargs):
  1381. """Plots a function of a single variable as a curve.
  1382. Parameters
  1383. ==========
  1384. args :
  1385. The first argument is the expression representing the function
  1386. of single variable to be plotted.
  1387. The last argument is a 3-tuple denoting the range of the free
  1388. variable. e.g. ``(x, 0, 5)``
  1389. Typical usage examples are in the following:
  1390. - Plotting a single expression with a single range.
  1391. ``plot(expr, range, **kwargs)``
  1392. - Plotting a single expression with the default range (-10, 10).
  1393. ``plot(expr, **kwargs)``
  1394. - Plotting multiple expressions with a single range.
  1395. ``plot(expr1, expr2, ..., range, **kwargs)``
  1396. - Plotting multiple expressions with multiple ranges.
  1397. ``plot((expr1, range1), (expr2, range2), ..., **kwargs)``
  1398. It is best practice to specify range explicitly because default
  1399. range may change in the future if a more advanced default range
  1400. detection algorithm is implemented.
  1401. show : bool, optional
  1402. The default value is set to ``True``. Set show to ``False`` and
  1403. the function will not display the plot. The returned instance of
  1404. the ``Plot`` class can then be used to save or display the plot
  1405. by calling the ``save()`` and ``show()`` methods respectively.
  1406. line_color : string, or float, or function, optional
  1407. Specifies the color for the plot.
  1408. See ``Plot`` to see how to set color for the plots.
  1409. Note that by setting ``line_color``, it would be applied simultaneously
  1410. to all the series.
  1411. title : str, optional
  1412. Title of the plot. It is set to the latex representation of
  1413. the expression, if the plot has only one expression.
  1414. label : str, optional
  1415. The label of the expression in the plot. It will be used when
  1416. called with ``legend``. Default is the name of the expression.
  1417. e.g. ``sin(x)``
  1418. xlabel : str or expression, optional
  1419. Label for the x-axis.
  1420. ylabel : str or expression, optional
  1421. Label for the y-axis.
  1422. xscale : 'linear' or 'log', optional
  1423. Sets the scaling of the x-axis.
  1424. yscale : 'linear' or 'log', optional
  1425. Sets the scaling of the y-axis.
  1426. axis_center : (float, float), optional
  1427. Tuple of two floats denoting the coordinates of the center or
  1428. {'center', 'auto'}
  1429. xlim : (float, float), optional
  1430. Denotes the x-axis limits, ``(min, max)```.
  1431. ylim : (float, float), optional
  1432. Denotes the y-axis limits, ``(min, max)```.
  1433. annotations : list, optional
  1434. A list of dictionaries specifying the type of annotation
  1435. required. The keys in the dictionary should be equivalent
  1436. to the arguments of the :external:mod:`matplotlib`'s
  1437. :external:meth:`~matplotlib.axes.Axes.annotate` method.
  1438. markers : list, optional
  1439. A list of dictionaries specifying the type the markers required.
  1440. The keys in the dictionary should be equivalent to the arguments
  1441. of the :external:mod:`matplotlib`'s :external:func:`~matplotlib.pyplot.plot()` function
  1442. along with the marker related keyworded arguments.
  1443. rectangles : list, optional
  1444. A list of dictionaries specifying the dimensions of the
  1445. rectangles to be plotted. The keys in the dictionary should be
  1446. equivalent to the arguments of the :external:mod:`matplotlib`'s
  1447. :external:class:`~matplotlib.patches.Rectangle` class.
  1448. fill : dict, optional
  1449. A dictionary specifying the type of color filling required in
  1450. the plot. The keys in the dictionary should be equivalent to the
  1451. arguments of the :external:mod:`matplotlib`'s
  1452. :external:meth:`~matplotlib.axes.Axes.fill_between` method.
  1453. adaptive : bool, optional
  1454. The default value is set to ``True``. Set adaptive to ``False``
  1455. and specify ``nb_of_points`` if uniform sampling is required.
  1456. The plotting uses an adaptive algorithm which samples
  1457. recursively to accurately plot. The adaptive algorithm uses a
  1458. random point near the midpoint of two points that has to be
  1459. further sampled. Hence the same plots can appear slightly
  1460. different.
  1461. depth : int, optional
  1462. Recursion depth of the adaptive algorithm. A depth of value
  1463. `n` samples a maximum of `2^{n}` points.
  1464. If the ``adaptive`` flag is set to ``False``, this will be
  1465. ignored.
  1466. nb_of_points : int, optional
  1467. Used when the ``adaptive`` is set to ``False``. The function
  1468. is uniformly sampled at ``nb_of_points`` number of points.
  1469. If the ``adaptive`` flag is set to ``True``, this will be
  1470. ignored.
  1471. size : (float, float), optional
  1472. A tuple in the form (width, height) in inches to specify the size of
  1473. the overall figure. The default value is set to ``None``, meaning
  1474. the size will be set by the default backend.
  1475. Examples
  1476. ========
  1477. .. plot::
  1478. :context: close-figs
  1479. :format: doctest
  1480. :include-source: True
  1481. >>> from sympy import symbols
  1482. >>> from sympy.plotting import plot
  1483. >>> x = symbols('x')
  1484. Single Plot
  1485. .. plot::
  1486. :context: close-figs
  1487. :format: doctest
  1488. :include-source: True
  1489. >>> plot(x**2, (x, -5, 5))
  1490. Plot object containing:
  1491. [0]: cartesian line: x**2 for x over (-5.0, 5.0)
  1492. Multiple plots with single range.
  1493. .. plot::
  1494. :context: close-figs
  1495. :format: doctest
  1496. :include-source: True
  1497. >>> plot(x, x**2, x**3, (x, -5, 5))
  1498. Plot object containing:
  1499. [0]: cartesian line: x for x over (-5.0, 5.0)
  1500. [1]: cartesian line: x**2 for x over (-5.0, 5.0)
  1501. [2]: cartesian line: x**3 for x over (-5.0, 5.0)
  1502. Multiple plots with different ranges.
  1503. .. plot::
  1504. :context: close-figs
  1505. :format: doctest
  1506. :include-source: True
  1507. >>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
  1508. Plot object containing:
  1509. [0]: cartesian line: x**2 for x over (-6.0, 6.0)
  1510. [1]: cartesian line: x for x over (-5.0, 5.0)
  1511. No adaptive sampling.
  1512. .. plot::
  1513. :context: close-figs
  1514. :format: doctest
  1515. :include-source: True
  1516. >>> plot(x**2, adaptive=False, nb_of_points=400)
  1517. Plot object containing:
  1518. [0]: cartesian line: x**2 for x over (-10.0, 10.0)
  1519. See Also
  1520. ========
  1521. Plot, LineOver1DRangeSeries
  1522. """
  1523. args = list(map(sympify, args))
  1524. free = set()
  1525. for a in args:
  1526. if isinstance(a, Expr):
  1527. free |= a.free_symbols
  1528. if len(free) > 1:
  1529. raise ValueError(
  1530. 'The same variable should be used in all '
  1531. 'univariate expressions being plotted.')
  1532. x = free.pop() if free else Symbol('x')
  1533. kwargs.setdefault('xlabel', x)
  1534. kwargs.setdefault('ylabel', Function('f')(x))
  1535. series = []
  1536. plot_expr = check_arguments(args, 1, 1)
  1537. series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr]
  1538. plots = Plot(*series, **kwargs)
  1539. if show:
  1540. plots.show()
  1541. return plots
  1542. def plot_parametric(*args, show=True, **kwargs):
  1543. """
  1544. Plots a 2D parametric curve.
  1545. Parameters
  1546. ==========
  1547. args
  1548. Common specifications are:
  1549. - Plotting a single parametric curve with a range
  1550. ``plot_parametric((expr_x, expr_y), range)``
  1551. - Plotting multiple parametric curves with the same range
  1552. ``plot_parametric((expr_x, expr_y), ..., range)``
  1553. - Plotting multiple parametric curves with different ranges
  1554. ``plot_parametric((expr_x, expr_y, range), ...)``
  1555. ``expr_x`` is the expression representing $x$ component of the
  1556. parametric function.
  1557. ``expr_y`` is the expression representing $y$ component of the
  1558. parametric function.
  1559. ``range`` is a 3-tuple denoting the parameter symbol, start and
  1560. stop. For example, ``(u, 0, 5)``.
  1561. If the range is not specified, then a default range of (-10, 10)
  1562. is used.
  1563. However, if the arguments are specified as
  1564. ``(expr_x, expr_y, range), ...``, you must specify the ranges
  1565. for each expressions manually.
  1566. Default range may change in the future if a more advanced
  1567. algorithm is implemented.
  1568. adaptive : bool, optional
  1569. Specifies whether to use the adaptive sampling or not.
  1570. The default value is set to ``True``. Set adaptive to ``False``
  1571. and specify ``nb_of_points`` if uniform sampling is required.
  1572. depth : int, optional
  1573. The recursion depth of the adaptive algorithm. A depth of
  1574. value $n$ samples a maximum of $2^n$ points.
  1575. nb_of_points : int, optional
  1576. Used when the ``adaptive`` flag is set to ``False``.
  1577. Specifies the number of the points used for the uniform
  1578. sampling.
  1579. line_color : string, or float, or function, optional
  1580. Specifies the color for the plot.
  1581. See ``Plot`` to see how to set color for the plots.
  1582. Note that by setting ``line_color``, it would be applied simultaneously
  1583. to all the series.
  1584. label : str, optional
  1585. The label of the expression in the plot. It will be used when
  1586. called with ``legend``. Default is the name of the expression.
  1587. e.g. ``sin(x)``
  1588. xlabel : str, optional
  1589. Label for the x-axis.
  1590. ylabel : str, optional
  1591. Label for the y-axis.
  1592. xscale : 'linear' or 'log', optional
  1593. Sets the scaling of the x-axis.
  1594. yscale : 'linear' or 'log', optional
  1595. Sets the scaling of the y-axis.
  1596. axis_center : (float, float), optional
  1597. Tuple of two floats denoting the coordinates of the center or
  1598. {'center', 'auto'}
  1599. xlim : (float, float), optional
  1600. Denotes the x-axis limits, ``(min, max)```.
  1601. ylim : (float, float), optional
  1602. Denotes the y-axis limits, ``(min, max)```.
  1603. size : (float, float), optional
  1604. A tuple in the form (width, height) in inches to specify the size of
  1605. the overall figure. The default value is set to ``None``, meaning
  1606. the size will be set by the default backend.
  1607. Examples
  1608. ========
  1609. .. plot::
  1610. :context: reset
  1611. :format: doctest
  1612. :include-source: True
  1613. >>> from sympy import plot_parametric, symbols, cos, sin
  1614. >>> u = symbols('u')
  1615. A parametric plot with a single expression:
  1616. .. plot::
  1617. :context: close-figs
  1618. :format: doctest
  1619. :include-source: True
  1620. >>> plot_parametric((cos(u), sin(u)), (u, -5, 5))
  1621. Plot object containing:
  1622. [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
  1623. A parametric plot with multiple expressions with the same range:
  1624. .. plot::
  1625. :context: close-figs
  1626. :format: doctest
  1627. :include-source: True
  1628. >>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10))
  1629. Plot object containing:
  1630. [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0)
  1631. [1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0)
  1632. A parametric plot with multiple expressions with different ranges
  1633. for each curve:
  1634. .. plot::
  1635. :context: close-figs
  1636. :format: doctest
  1637. :include-source: True
  1638. >>> plot_parametric((cos(u), sin(u), (u, -5, 5)),
  1639. ... (cos(u), u, (u, -5, 5)))
  1640. Plot object containing:
  1641. [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
  1642. [1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0)
  1643. Notes
  1644. =====
  1645. The plotting uses an adaptive algorithm which samples recursively to
  1646. accurately plot the curve. The adaptive algorithm uses a random point
  1647. near the midpoint of two points that has to be further sampled.
  1648. Hence, repeating the same plot command can give slightly different
  1649. results because of the random sampling.
  1650. If there are multiple plots, then the same optional arguments are
  1651. applied to all the plots drawn in the same canvas. If you want to
  1652. set these options separately, you can index the returned ``Plot``
  1653. object and set it.
  1654. For example, when you specify ``line_color`` once, it would be
  1655. applied simultaneously to both series.
  1656. .. plot::
  1657. :context: close-figs
  1658. :format: doctest
  1659. :include-source: True
  1660. >>> from sympy import pi
  1661. >>> expr1 = (u, cos(2*pi*u)/2 + 1/2)
  1662. >>> expr2 = (u, sin(2*pi*u)/2 + 1/2)
  1663. >>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue')
  1664. If you want to specify the line color for the specific series, you
  1665. should index each item and apply the property manually.
  1666. .. plot::
  1667. :context: close-figs
  1668. :format: doctest
  1669. :include-source: True
  1670. >>> p[0].line_color = 'red'
  1671. >>> p.show()
  1672. See Also
  1673. ========
  1674. Plot, Parametric2DLineSeries
  1675. """
  1676. args = list(map(sympify, args))
  1677. series = []
  1678. plot_expr = check_arguments(args, 2, 1)
  1679. series = [Parametric2DLineSeries(*arg, **kwargs) for arg in plot_expr]
  1680. plots = Plot(*series, **kwargs)
  1681. if show:
  1682. plots.show()
  1683. return plots
  1684. def plot3d_parametric_line(*args, show=True, **kwargs):
  1685. """
  1686. Plots a 3D parametric line plot.
  1687. Usage
  1688. =====
  1689. Single plot:
  1690. ``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)``
  1691. If the range is not specified, then a default range of (-10, 10) is used.
  1692. Multiple plots.
  1693. ``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)``
  1694. Ranges have to be specified for every expression.
  1695. Default range may change in the future if a more advanced default range
  1696. detection algorithm is implemented.
  1697. Arguments
  1698. =========
  1699. expr_x : Expression representing the function along x.
  1700. expr_y : Expression representing the function along y.
  1701. expr_z : Expression representing the function along z.
  1702. range : (:class:`~.Symbol`, float, float)
  1703. A 3-tuple denoting the range of the parameter variable, e.g., (u, 0, 5).
  1704. Keyword Arguments
  1705. =================
  1706. Arguments for ``Parametric3DLineSeries`` class.
  1707. nb_of_points : The range is uniformly sampled at ``nb_of_points``
  1708. number of points.
  1709. Aesthetics:
  1710. line_color : string, or float, or function, optional
  1711. Specifies the color for the plot.
  1712. See ``Plot`` to see how to set color for the plots.
  1713. Note that by setting ``line_color``, it would be applied simultaneously
  1714. to all the series.
  1715. label : str
  1716. The label to the plot. It will be used when called with ``legend=True``
  1717. to denote the function with the given label in the plot.
  1718. If there are multiple plots, then the same series arguments are applied to
  1719. all the plots. If you want to set these options separately, you can index
  1720. the returned ``Plot`` object and set it.
  1721. Arguments for ``Plot`` class.
  1722. title : str
  1723. Title of the plot.
  1724. size : (float, float), optional
  1725. A tuple in the form (width, height) in inches to specify the size of
  1726. the overall figure. The default value is set to ``None``, meaning
  1727. the size will be set by the default backend.
  1728. Examples
  1729. ========
  1730. .. plot::
  1731. :context: reset
  1732. :format: doctest
  1733. :include-source: True
  1734. >>> from sympy import symbols, cos, sin
  1735. >>> from sympy.plotting import plot3d_parametric_line
  1736. >>> u = symbols('u')
  1737. Single plot.
  1738. .. plot::
  1739. :context: close-figs
  1740. :format: doctest
  1741. :include-source: True
  1742. >>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5))
  1743. Plot object containing:
  1744. [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
  1745. Multiple plots.
  1746. .. plot::
  1747. :context: close-figs
  1748. :format: doctest
  1749. :include-source: True
  1750. >>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)),
  1751. ... (sin(u), u**2, u, (u, -5, 5)))
  1752. Plot object containing:
  1753. [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
  1754. [1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0)
  1755. See Also
  1756. ========
  1757. Plot, Parametric3DLineSeries
  1758. """
  1759. args = list(map(sympify, args))
  1760. series = []
  1761. plot_expr = check_arguments(args, 3, 1)
  1762. series = [Parametric3DLineSeries(*arg, **kwargs) for arg in plot_expr]
  1763. kwargs.setdefault("xlabel", "x")
  1764. kwargs.setdefault("ylabel", "y")
  1765. kwargs.setdefault("zlabel", "z")
  1766. plots = Plot(*series, **kwargs)
  1767. if show:
  1768. plots.show()
  1769. return plots
  1770. def plot3d(*args, show=True, **kwargs):
  1771. """
  1772. Plots a 3D surface plot.
  1773. Usage
  1774. =====
  1775. Single plot
  1776. ``plot3d(expr, range_x, range_y, **kwargs)``
  1777. If the ranges are not specified, then a default range of (-10, 10) is used.
  1778. Multiple plot with the same range.
  1779. ``plot3d(expr1, expr2, range_x, range_y, **kwargs)``
  1780. If the ranges are not specified, then a default range of (-10, 10) is used.
  1781. Multiple plots with different ranges.
  1782. ``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
  1783. Ranges have to be specified for every expression.
  1784. Default range may change in the future if a more advanced default range
  1785. detection algorithm is implemented.
  1786. Arguments
  1787. =========
  1788. expr : Expression representing the function along x.
  1789. range_x : (:class:`~.Symbol`, float, float)
  1790. A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
  1791. range_y : (:class:`~.Symbol`, float, float)
  1792. A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
  1793. Keyword Arguments
  1794. =================
  1795. Arguments for ``SurfaceOver2DRangeSeries`` class:
  1796. nb_of_points_x : int
  1797. The x range is sampled uniformly at ``nb_of_points_x`` of points.
  1798. nb_of_points_y : int
  1799. The y range is sampled uniformly at ``nb_of_points_y`` of points.
  1800. Aesthetics:
  1801. surface_color : Function which returns a float
  1802. Specifies the color for the surface of the plot.
  1803. See :class:`~.Plot` for more details.
  1804. If there are multiple plots, then the same series arguments are applied to
  1805. all the plots. If you want to set these options separately, you can index
  1806. the returned ``Plot`` object and set it.
  1807. Arguments for ``Plot`` class:
  1808. title : str
  1809. Title of the plot.
  1810. size : (float, float), optional
  1811. A tuple in the form (width, height) in inches to specify the size of the
  1812. overall figure. The default value is set to ``None``, meaning the size will
  1813. be set by the default backend.
  1814. Examples
  1815. ========
  1816. .. plot::
  1817. :context: reset
  1818. :format: doctest
  1819. :include-source: True
  1820. >>> from sympy import symbols
  1821. >>> from sympy.plotting import plot3d
  1822. >>> x, y = symbols('x y')
  1823. Single plot
  1824. .. plot::
  1825. :context: close-figs
  1826. :format: doctest
  1827. :include-source: True
  1828. >>> plot3d(x*y, (x, -5, 5), (y, -5, 5))
  1829. Plot object containing:
  1830. [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
  1831. Multiple plots with same range
  1832. .. plot::
  1833. :context: close-figs
  1834. :format: doctest
  1835. :include-source: True
  1836. >>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
  1837. Plot object containing:
  1838. [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
  1839. [1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
  1840. Multiple plots with different ranges.
  1841. .. plot::
  1842. :context: close-figs
  1843. :format: doctest
  1844. :include-source: True
  1845. >>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)),
  1846. ... (x*y, (x, -3, 3), (y, -3, 3)))
  1847. Plot object containing:
  1848. [0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0)
  1849. [1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0)
  1850. See Also
  1851. ========
  1852. Plot, SurfaceOver2DRangeSeries
  1853. """
  1854. args = list(map(sympify, args))
  1855. series = []
  1856. plot_expr = check_arguments(args, 1, 2)
  1857. series = [SurfaceOver2DRangeSeries(*arg, **kwargs) for arg in plot_expr]
  1858. kwargs.setdefault("xlabel", series[0].var_x)
  1859. kwargs.setdefault("ylabel", series[0].var_y)
  1860. kwargs.setdefault("zlabel", Function('f')(series[0].var_x, series[0].var_y))
  1861. plots = Plot(*series, **kwargs)
  1862. if show:
  1863. plots.show()
  1864. return plots
  1865. def plot3d_parametric_surface(*args, show=True, **kwargs):
  1866. """
  1867. Plots a 3D parametric surface plot.
  1868. Explanation
  1869. ===========
  1870. Single plot.
  1871. ``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)``
  1872. If the ranges is not specified, then a default range of (-10, 10) is used.
  1873. Multiple plots.
  1874. ``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)``
  1875. Ranges have to be specified for every expression.
  1876. Default range may change in the future if a more advanced default range
  1877. detection algorithm is implemented.
  1878. Arguments
  1879. =========
  1880. expr_x : Expression representing the function along ``x``.
  1881. expr_y : Expression representing the function along ``y``.
  1882. expr_z : Expression representing the function along ``z``.
  1883. range_u : (:class:`~.Symbol`, float, float)
  1884. A 3-tuple denoting the range of the u variable, e.g. (u, 0, 5).
  1885. range_v : (:class:`~.Symbol`, float, float)
  1886. A 3-tuple denoting the range of the v variable, e.g. (v, 0, 5).
  1887. Keyword Arguments
  1888. =================
  1889. Arguments for ``ParametricSurfaceSeries`` class:
  1890. nb_of_points_u : int
  1891. The ``u`` range is sampled uniformly at ``nb_of_points_v`` of points
  1892. nb_of_points_y : int
  1893. The ``v`` range is sampled uniformly at ``nb_of_points_y`` of points
  1894. Aesthetics:
  1895. surface_color : Function which returns a float
  1896. Specifies the color for the surface of the plot. See
  1897. :class:`~Plot` for more details.
  1898. If there are multiple plots, then the same series arguments are applied for
  1899. all the plots. If you want to set these options separately, you can index
  1900. the returned ``Plot`` object and set it.
  1901. Arguments for ``Plot`` class:
  1902. title : str
  1903. Title of the plot.
  1904. size : (float, float), optional
  1905. A tuple in the form (width, height) in inches to specify the size of the
  1906. overall figure. The default value is set to ``None``, meaning the size will
  1907. be set by the default backend.
  1908. Examples
  1909. ========
  1910. .. plot::
  1911. :context: reset
  1912. :format: doctest
  1913. :include-source: True
  1914. >>> from sympy import symbols, cos, sin
  1915. >>> from sympy.plotting import plot3d_parametric_surface
  1916. >>> u, v = symbols('u v')
  1917. Single plot.
  1918. .. plot::
  1919. :context: close-figs
  1920. :format: doctest
  1921. :include-source: True
  1922. >>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v,
  1923. ... (u, -5, 5), (v, -5, 5))
  1924. Plot object containing:
  1925. [0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0)
  1926. See Also
  1927. ========
  1928. Plot, ParametricSurfaceSeries
  1929. """
  1930. args = list(map(sympify, args))
  1931. series = []
  1932. plot_expr = check_arguments(args, 3, 2)
  1933. series = [ParametricSurfaceSeries(*arg, **kwargs) for arg in plot_expr]
  1934. kwargs.setdefault("xlabel", "x")
  1935. kwargs.setdefault("ylabel", "y")
  1936. kwargs.setdefault("zlabel", "z")
  1937. plots = Plot(*series, **kwargs)
  1938. if show:
  1939. plots.show()
  1940. return plots
  1941. def plot_contour(*args, show=True, **kwargs):
  1942. """
  1943. Draws contour plot of a function
  1944. Usage
  1945. =====
  1946. Single plot
  1947. ``plot_contour(expr, range_x, range_y, **kwargs)``
  1948. If the ranges are not specified, then a default range of (-10, 10) is used.
  1949. Multiple plot with the same range.
  1950. ``plot_contour(expr1, expr2, range_x, range_y, **kwargs)``
  1951. If the ranges are not specified, then a default range of (-10, 10) is used.
  1952. Multiple plots with different ranges.
  1953. ``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
  1954. Ranges have to be specified for every expression.
  1955. Default range may change in the future if a more advanced default range
  1956. detection algorithm is implemented.
  1957. Arguments
  1958. =========
  1959. expr : Expression representing the function along x.
  1960. range_x : (:class:`Symbol`, float, float)
  1961. A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
  1962. range_y : (:class:`Symbol`, float, float)
  1963. A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
  1964. Keyword Arguments
  1965. =================
  1966. Arguments for ``ContourSeries`` class:
  1967. nb_of_points_x : int
  1968. The x range is sampled uniformly at ``nb_of_points_x`` of points.
  1969. nb_of_points_y : int
  1970. The y range is sampled uniformly at ``nb_of_points_y`` of points.
  1971. Aesthetics:
  1972. surface_color : Function which returns a float
  1973. Specifies the color for the surface of the plot. See
  1974. :class:`sympy.plotting.Plot` for more details.
  1975. If there are multiple plots, then the same series arguments are applied to
  1976. all the plots. If you want to set these options separately, you can index
  1977. the returned ``Plot`` object and set it.
  1978. Arguments for ``Plot`` class:
  1979. title : str
  1980. Title of the plot.
  1981. size : (float, float), optional
  1982. A tuple in the form (width, height) in inches to specify the size of
  1983. the overall figure. The default value is set to ``None``, meaning
  1984. the size will be set by the default backend.
  1985. See Also
  1986. ========
  1987. Plot, ContourSeries
  1988. """
  1989. args = list(map(sympify, args))
  1990. plot_expr = check_arguments(args, 1, 2)
  1991. series = [ContourSeries(*arg) for arg in plot_expr]
  1992. plot_contours = Plot(*series, **kwargs)
  1993. if len(plot_expr[0].free_symbols) > 2:
  1994. raise ValueError('Contour Plot cannot Plot for more than two variables.')
  1995. if show:
  1996. plot_contours.show()
  1997. return plot_contours
  1998. def check_arguments(args, expr_len, nb_of_free_symbols):
  1999. """
  2000. Checks the arguments and converts into tuples of the
  2001. form (exprs, ranges).
  2002. Examples
  2003. ========
  2004. .. plot::
  2005. :context: reset
  2006. :format: doctest
  2007. :include-source: True
  2008. >>> from sympy import cos, sin, symbols
  2009. >>> from sympy.plotting.plot import check_arguments
  2010. >>> x = symbols('x')
  2011. >>> check_arguments([cos(x), sin(x)], 2, 1)
  2012. [(cos(x), sin(x), (x, -10, 10))]
  2013. >>> check_arguments([x, x**2], 1, 1)
  2014. [(x, (x, -10, 10)), (x**2, (x, -10, 10))]
  2015. """
  2016. if not args:
  2017. return []
  2018. if expr_len > 1 and isinstance(args[0], Expr):
  2019. # Multiple expressions same range.
  2020. # The arguments are tuples when the expression length is
  2021. # greater than 1.
  2022. if len(args) < expr_len:
  2023. raise ValueError("len(args) should not be less than expr_len")
  2024. for i in range(len(args)):
  2025. if isinstance(args[i], Tuple):
  2026. break
  2027. else:
  2028. i = len(args) + 1
  2029. exprs = Tuple(*args[:i])
  2030. free_symbols = list(set().union(*[e.free_symbols for e in exprs]))
  2031. if len(args) == expr_len + nb_of_free_symbols:
  2032. #Ranges given
  2033. plots = [exprs + Tuple(*args[expr_len:])]
  2034. else:
  2035. default_range = Tuple(-10, 10)
  2036. ranges = []
  2037. for symbol in free_symbols:
  2038. ranges.append(Tuple(symbol) + default_range)
  2039. for i in range(len(free_symbols) - nb_of_free_symbols):
  2040. ranges.append(Tuple(Dummy()) + default_range)
  2041. plots = [exprs + Tuple(*ranges)]
  2042. return plots
  2043. if isinstance(args[0], Expr) or (isinstance(args[0], Tuple) and
  2044. len(args[0]) == expr_len and
  2045. expr_len != 3):
  2046. # Cannot handle expressions with number of expression = 3. It is
  2047. # not possible to differentiate between expressions and ranges.
  2048. #Series of plots with same range
  2049. for i in range(len(args)):
  2050. if isinstance(args[i], Tuple) and len(args[i]) != expr_len:
  2051. break
  2052. if not isinstance(args[i], Tuple):
  2053. args[i] = Tuple(args[i])
  2054. else:
  2055. i = len(args) + 1
  2056. exprs = args[:i]
  2057. assert all(isinstance(e, Expr) for expr in exprs for e in expr)
  2058. free_symbols = list(set().union(*[e.free_symbols for expr in exprs
  2059. for e in expr]))
  2060. if len(free_symbols) > nb_of_free_symbols:
  2061. raise ValueError("The number of free_symbols in the expression "
  2062. "is greater than %d" % nb_of_free_symbols)
  2063. if len(args) == i + nb_of_free_symbols and isinstance(args[i], Tuple):
  2064. ranges = Tuple(*list(args[
  2065. i:i + nb_of_free_symbols]))
  2066. plots = [expr + ranges for expr in exprs]
  2067. return plots
  2068. else:
  2069. # Use default ranges.
  2070. default_range = Tuple(-10, 10)
  2071. ranges = []
  2072. for symbol in free_symbols:
  2073. ranges.append(Tuple(symbol) + default_range)
  2074. for i in range(nb_of_free_symbols - len(free_symbols)):
  2075. ranges.append(Tuple(Dummy()) + default_range)
  2076. ranges = Tuple(*ranges)
  2077. plots = [expr + ranges for expr in exprs]
  2078. return plots
  2079. elif isinstance(args[0], Tuple) and len(args[0]) == expr_len + nb_of_free_symbols:
  2080. # Multiple plots with different ranges.
  2081. for arg in args:
  2082. for i in range(expr_len):
  2083. if not isinstance(arg[i], Expr):
  2084. raise ValueError("Expected an expression, given %s" %
  2085. str(arg[i]))
  2086. for i in range(nb_of_free_symbols):
  2087. if not len(arg[i + expr_len]) == 3:
  2088. raise ValueError("The ranges should be a tuple of "
  2089. "length 3, got %s" % str(arg[i + expr_len]))
  2090. return args