如何使用matplotlib显示图例

时间:2018-11-08 14:10:11

标签: python python-2.7 matplotlib

我试图使图例出现在matplotlib中,以便显示r ^ 2值,但图例将不会显示。任何帮助将非常感激。

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# Filling in the values obtained in the real image experiment
object_distance = np.array(range(15, 66, 5))
object_distance_error = 0.1
real_image_distance = np.array([29.5, 21.0, 17.4, 15.4, 14.3, 13.7, 13.1, 13.0, 12.6, 12.3, 12.3])
real_image_distance_error = 0.1
real_image_size = np.array([3.6, 2.0, 1.4, 1.0, 0.8, 0.7, 0.5, 0.45, 0.4, 0.4, 0.35])
real_image_size_error = 0.1
real_focus = 10

inverse_obj = 1.0/object_distance
inverse_rl_img = 1.0/real_image_distance
rl_slope, rl_intercept, rl_r_value, rl_p_value, rl_std_err = stats.linregress(inverse_obj, inverse_rl_img)
rl_line = inverse_obj*rl_slope + rl_intercept
r_squared = str(round(rl_r_value**2, 4))


fig1 = plt.figure()
fig1.set_size_inches(10, 10)
plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3)
plt.plot(inverse_obj, rl_line)

plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.legend([rl_line], [r"$r^2$" + r_squared])
plt.title("Graph of 1/s vs 1/s'")
plt.show()

2 个答案:

答案 0 :(得分:0)

您正在尝试在同一命令中定义文字图例和绘图,为此进行更改:

fig1 = plt.figure()
fig1.set_size_inches(10, 10)
plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3, label='rl_line')
plt.plot(inverse_obj, rl_line, label='$r^2$ + r_squared')
plt.legend()

plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.title("Graph of 1/s vs 1/s'")
plt.show()

请记住,plt.legend()只是在图形内部调用图例的方法。要定义图例,请使用plt.plot(label='rl_line')

答案 1 :(得分:0)

您也可以使用patches

import matplotlib.patches as mpatches

然后定义例如red_patch

red_patch = mpatches.Patch(color='red', label=f'r\u00b2={r_squared}')

并将其添加到plt.legend()

plt.legend(handles=[red_patch], ...)

您会得到这样的东西:

enter image description here