使用多个范围时Python SymPy的绘图图例 [英] Python SymPy's plotting legend when using multiple ranges

查看:66
本文介绍了使用多个范围时Python SymPy的绘图图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SymPy 的绘图模块,但是当我开始使用具有不同范围的多行时,图例停止工作(绘制函数 f(x),其定义取决于 x,如下例所示).实际上,我在任何地方都没有看到任何这样的示例:

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

而不是指定plt [0],但Python会说

instead of specifying plt[0] but Python says

具有多个元素的数组的真值是不明确的.使用a.any()或a.all()

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我的最终目标是具有多种颜色的线的图,表示在给定值之前和之后具有不同定义的函数x 我将它们附加在一起,例如,如果plt1和plt2都有两个部分,

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.

推荐答案

最简单的方法是直接使用matplotlib.您可以向sympy询问要绘制的点的列表,然后将它们自己与matplotlib一起使用,如下所示:

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()  

然后,您可以使用matplotlib的图例功能.

Then you can use matplotlib's legend function.

这篇关于使用多个范围时Python SymPy的绘图图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆