簡體   English   中英

如何獲得此圖以在情節上顯示圖例?

[英]How do I get this to show the legend on the 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'])

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM