python - 我如何让它在情节上显示图例?

标签 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)

最佳答案

您需要指定 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

关于python - 我如何让它在情节上显示图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41508888/

相关文章:

python - Django:注释每个对象的重复值个数的计数

python - 提取数字后跟单词

matplotlib - 动态绘图适用于 IDLE,但不适用于 jupyter notebook

Matlab 中的 imagesc() 不显示等 Axis

python - matplotlib:通过迭代相关的灰度为线图着色

Python;名称绑定(bind)不是对象引用?

python - 获取 CSV 文件中特定范围的数据 (Python)

python - yticks 的字体大小出乎意料地可变

python - matplotlib 怪异,它没有绘制我的图表

Python Matplotlib - 显示与标绘点相关的刻度线