I am using SymPy’s plotting module, but legends stop working when I start having multiple lines with different ranges (to plot a function f(x) whose definition depend on x like in the following example). I actually haven’t seen any example of this anywhere :
from sympy import * plt = plot((x**2,(x,-1,0)),(x**3,(x,0,1)),label='$f(x)$',show=False) plt[0].legend = True plt.show()
Here the legend is ignored. I also tried
plt.legend = True
instead of specifying plt[0] but Python says
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
My final goal would be something like a plot with lines of multiple colors, representing functions which have a different definition before and after a given value of x and I append them together, say, if plt1 and plt2 have both 2 parts,
plt = plt1 plt.append(plt2[0]) plt.append(plt2[1])
Does anyone know how label and legend work in this context? Thank you.
Advertisement
Answer
The simplest thing is to use matplotlib directly. You can ask sympy for the list of points that it would plot and then use them with matplotlib yourself like this:
In [9]: import sympy In [10]: line1, line2 = sympy.plot((x**2,(x,-1,0)),(x**3,(x,0,1)),label='$f(x)$',show=False) In [11]: x1, y1 = line1.get_points() In [12]: import matplotlib.pyplot as plt In [13]: plt.plot(x1, y1) Out[13]: [<matplotlib.lines.Line2D at 0x120a9da90>] In [14]: plt.show()
Then you can use matplotlib’s legend function.