Home > Blockchain >  Python & Sympy : How to plot a dashed line with plot_implicit?
Python & Sympy : How to plot a dashed line with plot_implicit?

Time:07-14

I'm trying to plot the graph of x = 1 in dashed style using plot_implicit of Sympy. But so far, I can't find a way to do it and can only change its color. Please have a look at my codes and the picture below and guide me on how to do it.

Thank you

Code:

x, y = symbols('x y')
p1 = plot_implicit(And(x > 1, y >= x**2), show=False)
p2 = plot_implicit(Eq(x, 1), line_color='crimson', show=False)
p3 = plot_implicit(Eq(x**2, y), line_color='crimson', show=False)

p1.append(p2[0])
p1.append(p3[0])

p1.show()

enter image description here

CodePudding user response:

With the current plotting module (Sympy 1.10.1) you cannot set linestyles directly. Moreover, plot_implicit is using matplotlib's fill and contour commands (depending on what expression you are trying to plot and on the value of the adaptive option).

We need to use a different approach:

  1. Generally, we could use the plot function to create line plots. However, it's impossible to plot the vertical line.
  2. Which leads to a mixed approach between matplotlib, sympy (and in some cases, numpy too), like this:

(Note: I've tried this on a Jupyter Notebook)

x, y = symbols('x y')
# generally, plot_implicit is going to create a fill
p1 = plot_implicit(And(x > 1, y >= x**2), (x, -10, 10), show=False)
# plot is going to create lines
p2 = plot(x**2, line_color='crimson', show=False)
p1.append(p2[0])
p1.show()

# access the matplotlib axes
# for demonstration purpose, set a dotted line style on the parabola
p1._backend.ax[0].lines[0].set_linestyle(":")
# add a vertical line at x=1 with a dashed linestyle
p1._backend.ax[0].axvline(1, color='crimson', linestyle="--")

enter image description here

  • Related