python画散点图带直线和图例_带图例的Matplotlib散点图有两种⽅法。其中⼀个给你每⼀个你策划的东西的图例条⽬,另⼀个让你把你想要的东西放在图例中,从this答案中⼤量窃取。
第⼀种⽅法是:import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,100)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
#Plot something
ax.plot(x,x, color='red', ls="-", label="$P_1(x)$")
ax.plot(x,0.5 * (3*x**2-1), color='green', ls="--", label="$P_2(x)$")
ax.plot(x,0.5 * (5*x**3-3*x), color='blue', ls=":", label="$P_3(x)$")
ax.legend()
plt.show()
ax.legend()函数有不⽌⼀个⽤途,第⼀个⽤途是根据axes对象中的⾏创建图例,第⼆个⽤途是⼿动控制条⽬,本⽂将对其进⾏描述。
您基本上需要给图例提供⾏句柄和相关的标签。
另⼀种⽅法是,通过创建Artist对象和标签,并将它们传递给ax.legend()函数,您可以在图例中放置所需的任何内容。你可以⽤它只把你的⼀些线放在传说中,或者你可以⽤它把你想要的东西放在传说中。import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,100)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
#Plot something
p1, = ax.plot(x,x, color='red', ls="-", label="$P_1(x)$")
p2, = ax.plot(x,0.5 * (3*x**2-1), color='green', ls="--", label="$P_2(x)$")
p3, = ax.plot(x,0.5 * (5*x**3-3*x), color='blue', ls=":", label="$P_3(x)$")
#Create legend from custom artist/label lists
ax.legend([p1,p2], ["$P_1(x)$", "$P_2(x)$"])
plt.show()
或者在这⾥,我们创建新的Line2D对象,并将它们赋给图例。import matplotlib.pyplot as pltit|delete|flag import numpy as np
import matplotlib.patches as mpatches
x = np.linspace(-1,1,100)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
matplotlib中subplot#Plot something
p1, = ax.plot(x,x, color='red', ls="-", label="$P_1(x)$")
p2, = ax.plot(x,0.5 * (3*x**2-1), color='green', ls="--", label="$P_2(x)$")
p3, = ax.plot(x,0.5 * (5*x**3-3*x), color='blue', ls=":", label="$P_3(x)$")
fakeLine1 = plt.Line2D([0,0],[0,1], color='Orange', marker='o', linestyle='-')
fakeLine2 = plt.Line2D([0,0],[0,1], color='Purple', marker='^', linestyle='')
fakeLine3 = plt.Line2D([0,0],[0,1], color='LightBlue', marker='*', linestyle=':')
#Create legend from custom artist/label lists
ax.legend([fakeLine1,fakeLine2,fakeLine3], ["label 1", "label 2", "label 3"])
plt.show()
我还尝试使⽤patches使该⽅法⼯作,如matplotlib图例指南页上的那样,但它似乎不⼯作,所以我放弃了。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。