[파이썬] matplotlib 범례 추가하기

Matplotlib is a powerful library in Python for creating visualizations and plots. One important aspect of creating informative plots is to include a legend that provides a clear explanation of the different elements in the plot. A legend helps the viewers understand the meaning of the different colors, markers, or lines used in the plot.

In this blog post, we will walk through the process of adding a legend to a matplotlib plot using Python code.

Prerequisites

Before we begin, make sure you have Matplotlib installed in your Python environment. You can install it using pip:

pip install matplotlib

Creating a Simple Plot

Let’s start by creating a simple line plot using Matplotlib. Suppose we have the following data:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')

plt.xlabel('x')
plt.ylabel('y')
plt.title('Simple Plot')
plt.legend()

plt.show()

In the code above, we first import matplotlib.pyplot as plt and numpy as np. We then define an array x using np.linspace to generate 100 evenly spaced values between 0 and 10. We also compute two arrays y1 and y2 representing the values of sine and cosine of x, respectively.

Next, we use plt.plot to create two line plots, one for y1 and one for y2. We provide a label argument to each plt.plot call to specify the label for each line plot.

After that, we set the x-axis label, y-axis label, and plot title using plt.xlabel, plt.ylabel, and plt.title, respectively.

Finally, we call plt.legend to add the legend to the plot. This will automatically use the labels provided in the plt.plot calls.

When we run the code, we should see a simple plot with two line plots and a legend indicating the meaning of each line.

Customizing the Legend

Matplotlib provides several options for customizing the appearance of the legend. Here are a few examples:

These are just a few examples of how you can customize the legend. The plt.legend function accepts many other arguments for further customization.

Conclusion

Adding a legend to a matplotlib plot is essential for providing a clear explanation of the different elements in the plot. By using the plt.legend function, we can easily add a legend to our plots and customize its appearance to suit our needs.

Matplotlib offers a lot of flexibility in creating visualizations, and the ability to add legends adds to its power for conveying information effectively. Let’s make our plots more informative and visually appealing by including legends in our matplotlib plots.