Understanding Matplotlib Legend Display

Asked 2 years ago, Updated 2 years ago, 86 views

In order to display multiple line graphs on a single graph in matplotlib's pyplot, I would like you to teach me how to attach legends.

Now, multiple lines are stored in one variable and can be drawn in a single pyplot.At that time, I don't know how to add a legend.

The following example shows the sine and cosine functions of a trigonometric function at once, but how should I add a legend?(I didn't know what to do with the label argument)

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace (1,10,100)

y1 = np.sin(x).reshape(-1,1)
y2 = np.cos(x).reshape(-1,1)
y=np.concatenate([y1,y2],axis=1)

plt.plot(x,y,label=)
plt.legend()

When I looked up the net, there was an example of drawing pyplots separately and specifying label as an argument each time, but I couldn't find an example of how to display the legend at once.

python matplotlib

2022-09-30 17:10

1 Answers

It was resolved by the reference posted by metropolis.Thank you.

As an overview, it appeared that each of the multiple line graphs was stored in a variable and the corresponding label was corresponding within plt.legend.

Here is a quote from a post by a person named Milla Well:

from numpy import*
from matplotlib.pyplot import*
from numpy.random import*

a=land(4,4)
a
>>array ([0.33562406, 0.96967617, 0.69730654, 0.46542408],
   [ 0.85707323,  0.37398595,  0.82455736,  0.72127002],
   [ 0.19530943,  0.4376796 ,  0.62653007,  0.77490795],
   [ 0.97362944,  0.42720348,  0.45379479,  0.75714877]])

[b,c,d,e] = lot(a)
legend([b,c,d,e],["b", "c", "d", "e", loc=1)
show()


2022-09-30 17:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.