简体   繁体   English

如何使用 matplotlib 显示图例

[英]How to display a legend with matplotlib

I am trying to get a legend to appear in matplotlib in order to display an r^2 value but the legend will not display.我试图让图例出现在 matplotlib 中以显示 r^2 值,但图例不会显示。 Any help would be much appreciated.任何帮助将非常感激。

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()

You are trying define the text legend and plot in the same command, change for this:您正在尝试在同一命令中定义文本图例和绘图,为此更改:

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()

Remember that plt.legend() is just a method which calls a legend inside the graph.请记住, plt.legend()只是一种在图形内调用图例的方法。 To define the legend use plt.plot(label='rl_line') for example.例如,要定义图例,请使用plt.plot(label='rl_line')

You can also use patches :您还可以使用patches

import matplotlib.patches as mpatches

then define eg red_patch :然后定义例如red_patch

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

and add it in plt.legend() ,并将其添加到plt.legend()

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

you'll get something like this:你会得到这样的东西:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM