简体   繁体   English

如何为每个子图添加图例

[英]How to add a legend to each subplot

I have 4 subplots with 4 different lines and I want to make a legend in the upper right corner of each subplot that only shows the line associated with that subplot. 我有4个子图,有4个不同的线,我想在每个子图的右上角创建一个图例,只显示与该子图关联的线。 How do I do that? 我怎么做? I tried subplot1.legend() but it throws an error. 我尝试了subplot1.legend()但它抛出了一个错误。

Code for subplot1: subplot1的代码:

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

figure = plt.figure("Figure")
subplot1 = figure.add_subplot(2,2,1)
x = np.linspace (0, 1.0, 200) 
y1 = beta.pdf(x, 10, 7)
subplot1.plot(x, y1, "-", label="r'$\alpha=10, \beta=7$'")
subplot1.legend() #throws an error when I include this statement
plt.show()

Found the answer! 找到答案了! I had a typo in my label. 我的标签上有一个拼写错误。 I changed the label to: 我将标签更改为:

subplot1.plot(x, y1, "-", label=(r'$\alpha=21, \beta=11$'))

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

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