plot_implicit.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. """Implicit plotting module for SymPy.
  2. Explanation
  3. ===========
  4. The module implements a data series called ImplicitSeries which is used by
  5. ``Plot`` class to plot implicit plots for different backends. The module,
  6. by default, implements plotting using interval arithmetic. It switches to a
  7. fall back algorithm if the expression cannot be plotted using interval arithmetic.
  8. It is also possible to specify to use the fall back algorithm for all plots.
  9. Boolean combinations of expressions cannot be plotted by the fall back
  10. algorithm.
  11. See Also
  12. ========
  13. sympy.plotting.plot
  14. References
  15. ==========
  16. .. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
  17. Mathematical Formulae with Two Free Variables.
  18. .. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
  19. Arithmetic. Master's thesis. University of Toronto, 1996
  20. """
  21. from sympy.core.containers import Tuple
  22. from sympy.core.symbol import (Dummy, Symbol)
  23. from sympy.polys.polyutils import _sort_gens
  24. from sympy.plotting.series import ImplicitSeries, _set_discretization_points
  25. from sympy.plotting.plot import plot_factory
  26. from sympy.utilities.decorator import doctest_depends_on
  27. from sympy.utilities.iterables import flatten
  28. __doctest_requires__ = {'plot_implicit': ['matplotlib']}
  29. @doctest_depends_on(modules=('matplotlib',))
  30. def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0,
  31. n=300, line_color="blue", show=True, **kwargs):
  32. """A plot function to plot implicit equations / inequalities.
  33. Arguments
  34. =========
  35. - expr : The equation / inequality that is to be plotted.
  36. - x_var (optional) : symbol to plot on x-axis or tuple giving symbol
  37. and range as ``(symbol, xmin, xmax)``
  38. - y_var (optional) : symbol to plot on y-axis or tuple giving symbol
  39. and range as ``(symbol, ymin, ymax)``
  40. If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
  41. expression will be assigned in the order they are sorted.
  42. The following keyword arguments can also be used:
  43. - ``adaptive`` Boolean. The default value is set to True. It has to be
  44. set to False if you want to use a mesh grid.
  45. - ``depth`` integer. The depth of recursion for adaptive mesh grid.
  46. Default value is 0. Takes value in the range (0, 4).
  47. - ``n`` integer. The number of points if adaptive mesh grid is not
  48. used. Default value is 300. This keyword argument replaces ``points``,
  49. which should be considered deprecated.
  50. - ``show`` Boolean. Default value is True. If set to False, the plot will
  51. not be shown. See ``Plot`` for further information.
  52. - ``title`` string. The title for the plot.
  53. - ``xlabel`` string. The label for the x-axis
  54. - ``ylabel`` string. The label for the y-axis
  55. Aesthetics options:
  56. - ``line_color``: float or string. Specifies the color for the plot.
  57. See ``Plot`` to see how to set color for the plots.
  58. Default value is "Blue"
  59. plot_implicit, by default, uses interval arithmetic to plot functions. If
  60. the expression cannot be plotted using interval arithmetic, it defaults to
  61. a generating a contour using a mesh grid of fixed number of points. By
  62. setting adaptive to False, you can force plot_implicit to use the mesh
  63. grid. The mesh grid method can be effective when adaptive plotting using
  64. interval arithmetic, fails to plot with small line width.
  65. Examples
  66. ========
  67. Plot expressions:
  68. .. plot::
  69. :context: reset
  70. :format: doctest
  71. :include-source: True
  72. >>> from sympy import plot_implicit, symbols, Eq, And
  73. >>> x, y = symbols('x y')
  74. Without any ranges for the symbols in the expression:
  75. .. plot::
  76. :context: close-figs
  77. :format: doctest
  78. :include-source: True
  79. >>> p1 = plot_implicit(Eq(x**2 + y**2, 5))
  80. With the range for the symbols:
  81. .. plot::
  82. :context: close-figs
  83. :format: doctest
  84. :include-source: True
  85. >>> p2 = plot_implicit(
  86. ... Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))
  87. With depth of recursion as argument:
  88. .. plot::
  89. :context: close-figs
  90. :format: doctest
  91. :include-source: True
  92. >>> p3 = plot_implicit(
  93. ... Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)
  94. Using mesh grid and not using adaptive meshing:
  95. .. plot::
  96. :context: close-figs
  97. :format: doctest
  98. :include-source: True
  99. >>> p4 = plot_implicit(
  100. ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
  101. ... adaptive=False)
  102. Using mesh grid without using adaptive meshing with number of points
  103. specified:
  104. .. plot::
  105. :context: close-figs
  106. :format: doctest
  107. :include-source: True
  108. >>> p5 = plot_implicit(
  109. ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
  110. ... adaptive=False, n=400)
  111. Plotting regions:
  112. .. plot::
  113. :context: close-figs
  114. :format: doctest
  115. :include-source: True
  116. >>> p6 = plot_implicit(y > x**2)
  117. Plotting Using boolean conjunctions:
  118. .. plot::
  119. :context: close-figs
  120. :format: doctest
  121. :include-source: True
  122. >>> p7 = plot_implicit(And(y > x, y > -x))
  123. When plotting an expression with a single variable (y - 1, for example),
  124. specify the x or the y variable explicitly:
  125. .. plot::
  126. :context: close-figs
  127. :format: doctest
  128. :include-source: True
  129. >>> p8 = plot_implicit(y - 1, y_var=y)
  130. >>> p9 = plot_implicit(x - 1, x_var=x)
  131. """
  132. xyvar = [i for i in (x_var, y_var) if i is not None]
  133. free_symbols = expr.free_symbols
  134. range_symbols = Tuple(*flatten(xyvar)).free_symbols
  135. undeclared = free_symbols - range_symbols
  136. if len(free_symbols & range_symbols) > 2:
  137. raise NotImplementedError("Implicit plotting is not implemented for "
  138. "more than 2 variables")
  139. #Create default ranges if the range is not provided.
  140. default_range = Tuple(-5, 5)
  141. def _range_tuple(s):
  142. if isinstance(s, Symbol):
  143. return Tuple(s) + default_range
  144. if len(s) == 3:
  145. return Tuple(*s)
  146. raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s)
  147. if len(xyvar) == 0:
  148. xyvar = list(_sort_gens(free_symbols))
  149. var_start_end_x = _range_tuple(xyvar[0])
  150. x = var_start_end_x[0]
  151. if len(xyvar) != 2:
  152. if x in undeclared or not undeclared:
  153. xyvar.append(Dummy('f(%s)' % x.name))
  154. else:
  155. xyvar.append(undeclared.pop())
  156. var_start_end_y = _range_tuple(xyvar[1])
  157. kwargs = _set_discretization_points(kwargs, ImplicitSeries)
  158. series_argument = ImplicitSeries(
  159. expr, var_start_end_x, var_start_end_y,
  160. adaptive=adaptive, depth=depth,
  161. n=n, line_color=line_color)
  162. #set the x and y limits
  163. kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
  164. kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
  165. # set the x and y labels
  166. kwargs.setdefault('xlabel', var_start_end_x[0])
  167. kwargs.setdefault('ylabel', var_start_end_y[0])
  168. p = plot_factory(series_argument, **kwargs)
  169. if show:
  170. p.show()
  171. return p