如何让它在情节中显示传奇?

时间:2017-01-06 15:32:52

标签: python matplotlib plot

我想让这段代码显示一个传奇,但我尝试的一切都无法正常工作。这是我的代码。我过去尝试过put.legend(),它对我有用,我很困惑,为什么这不起作用。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

#declaring my plot
fig1 = plt.figure()

#declaring xvalues
xes = np.arange(-10, 10, 0.01)
xlen = len(xes)
#zeros for yvalues along the axis
yes = np.zeros(xlen)

#declaring my variables
Efieldx = np.zeros((xlen, 1))
Efieldy = np.zeros((xlen, 1))

#locations of my two particles
p1x = 0;
p1y = 1;
p2x = 0;
p2y = -1
q = 1;

Efieldx1  = q/((xes-p1x)*(xes-p1x) + (yes-p1y)*(yes-p1y))**(1.5)*(xes-p1x)
Efieldy1  = q/((xes-p1x)*(xes-p1x) + (yes-p1y)*(yes-p1y))**(1.5)*(yes-p1y)
Efieldx2  = q/((xes-p2x)*(xes-p2x) + (yes-p2y)*(yes-p2y))**(1.5)*(xes-p2x)
Efieldy2  = q/((xes-p1x)*(xes-p1x) + (yes-p1y)*(yes-p1y))**(1.5)*(yes-p2y)
Efieldx = Efieldx1 + Efieldx2
Efieldy = Efieldy1 + Efieldy2 
#Efieldx  = -1/(xs * xs + ys * ys)^(0.5)


#let's define a function instead:
def f_Efield(q, x, y, xs, ys):
    Ex  = q*((xs-x)*(xs-x) + (ys-y)*(ys-y))**(-1.5)*(xs-x)
    Ey  = q/((xs-x)*(xs-x) + (ys-y)*(ys-y))**(1.5)*(ys-y)
    return Ex, Ey

#using my new function
Exhere, Eyhere = f_Efield(2, 0, 0,xes, yes)

#plotting:
l, = plt.plot(xes, Efieldx, 'g-')
l, = plt.plot(xes, Exhere, 'r--')
plt.xlim(-10, 10)
plt.ylim(-2, 2)
plt.xlabel('x')
plt.title('Electric field along x-direction \n Andrew Richardson')
#adding a legend
plt.legend()
#displaying the plot
plt.show()

#saving the plot
fig1.savefig('Efield.pdf')

Exhere, Eyhere = f_Efield(-1, 0, 0, xes, yes)

1 个答案:

答案 0 :(得分:4)

您需要为您的图表指定label属性或为您调用legend传递句柄(可选但建议)和标签,否则matplotlib无法知道要放入哪个文本图例

# Using label kwarg
plt.plot(xes, Efieldx, 'g-', label='Efieldx')
plt.plot(xes, Exhere, 'r--', label='Exhere')
plt.legend()

# Using explicit plot handles and labels
p1 = plt.plot(xes, Efieldx, 'g-')
p2 = plt.plot(xes, Exhere, 'r--')
plt.legend([p1, p2], ['Efieldx', 'Exhere'])

# Using just the labels (not recommended)
plt.plot(xes, Efieldx, 'g-')
plt.plot(xes, Exhere, 'r--')
plt.legend(['Efieldx', 'Exhere'])

enter image description here