## PyPlot Module in Python: Understanding Legends in Graphs

Data analysis and graphical visualisation are two essential components in machine learning. As we understand more about data, the graphs and charts that we create become increasingly complex.

Therefore, adding labels and legends to our plots becomes essential to convey the accurate message that the data presents. In this article, we will delve into the basics of PyPlot, a module in Python.

We will also explore the importance of legends in graphs and learn how to add customized ones to our plots.

## Functionality of PyPlot Module

Matplotlib library, which incorporates the PyPlot module, is an open-source package that helps in the creation of graphs and other visualizations in Python. PyPlot assists in the creation of multi-dimensional graphical displays in an interactive way while allowing for customization and flexibility.

It is used to create line charts, scatter plot, histograms, and bar graphs, which can be used for data distributions, identifying and tracking trends, and comparing data sets.

### Types of Graphs

**Line charts:**These charts show data changing over time, usually as a point connected by a line. The line shows the trend of the data over a period.**Scatter plot:**This chart plots individual data points in terms of two continuous variables, one for the x-axis and the other for the y-axis. Scatter plots are beneficial in showing the relationship between two different sets of data.**Bar graphs:**This chart is a graphical presentation of categorical data with rectangular bars having lengths proportional to the values that they represent.**Histograms:**Histograms show the distribution of data in a set of continuous numerical variables by using bars that cover ranges of values and representing frequencies.

## Adding Legend Using Label Parameter of Plot()

In Matplotlib, a legend plays a vital role in the analysis of data because it represents different data sets plotted on the same graph. A legend helps in differentiating between the data sets and helps the reader comprehend the story that the data represents.

In the Pyplot module, adding a legend to a plot is a simple process that requires specifying a label parameter in the plot function. For example, if we plot a linear equation, we can label the graph with “Linear Equation Y=mx+c” by simply specifying the label parameter in the plot function.

The below code shows how we can execute it.

import matplotlib.pyplot as plt

import numpy as np

# Linear Equation Y=mx+c

x = np.linspace(0, 10, 50)

y = 2*x + 1

plt.plot(x, y, 'r', linewidth=1.5, label='Linear Equation Y=mx+c')

plt.legend(loc='upper left')

plt.show()

In the above example, the legend() function is used to place the legend at the upper-left corner of the plot. The legend() function can be used to add customized legends using iterables, clubs, percentages, pie charts, colors, and many more.

## Customized Legends in PyPlot

The Pyplot module allows us to customize our legends to represent multiple data sets. A custom legend can be created using the iterable feature in Python, allowing the inclusion of new handles and labels.

The following example demonstrates how to create a custom legend using an iterable object.

import matplotlib.pyplot as plt

import random

# Plotting random data

for i in range(5):

plt.plot([random.randint(0, 10) for j in range(10)], label='Line' + str(i+1))

# Creating custom Legend

handles, labels = plt.gca().get_legend_handles_labels()

order = [0, 2, 1, 3, 4]

plt.legend([handles[idx] for idx in order], [labels[idx] for idx in order], loc='best')

plt.show()

In the above example, we plot five lines with different labels. The get_legend_handles_labels() function retrieves a tuple containing the handles used on the current plot and their corresponding labels.

The handles and labels command retrieves the tuple value in two different variables. To customize our legend, we need to specify the order in which the legend must appear.

## Assigning Colors to Graphs

Adding colors to our graphs helps us differentiate the data sets. In PyPlot, to assign colors to our graphs and legends, we can pass in any of the possible colors by passing them as a parameter to the plot() or scatter() method.

We can use the color codes mentioned below in our function to customize the line or marker color for the graph.

import matplotlib.pyplot as plt

import numpy as np

# Linear Equation Y=mx+c

x = np.linspace(0, 10, 50)

y = 2*x + 1

plt.plot(x, y, color='red', linewidth=2.0, label='Linear Equation Y=mx+c')

plt.legend(loc='upper left')

plt.show()

## Conclusion

The PyPlot module in Python is an essential tool in data analysis, allowing professionals to create multiple types of graphs, legends, and color-coded charts for efficient data representation. In this article, we explored the importance of legends in graphs and learned how to add customized ones to our plots using PyPlot.

We also gained insight into how to differentiate data plots using color codes. Implement these concepts to create the perfect chart that meets your visualization requirement.

## PyPlot Code Examples: Techniques for Beginners

Data interpretation and analysis are now easier with the help of PyPlot module in Python. The ability to create multi-dimensional graphical representations of data helps professionals understand more about data trends and patterns.

In this article, we will learn how to plot line graphs, pie charts, and customize our graphs to represent meaningful data trends.

### Plotting a Line Graph

Line graphs are useful in displaying changes over time. It is a vital tool in identifying patterns and trends in data recording.

Below is an example of how you can plot a line graph using PyPlot’s plot() function.

import matplotlib.pyplot as plt

import numpy as np

# X-axis values

x = np.arange(0, 5, 0.1)

# Y-axis values

y = x**2

# Plotting line graph

plt.plot(x, y, color='red', linestyle='-', linewidth=2)

# Setting labels for X and Y-axis

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

# Adding title to the plot

plt.title('Line Graph Example')

# Display Plot

plt.show()

In the above example, the plot() function is used to create a linear line graph. The np.arange() function specifies the range that the X-axis covers, and the Y-axis values are determined by the equation “y = x**2.” The red color, line style and width are also specified, followed by the X-axis and Y-axis labels, and plot title.

### Plotting a Pie Chart

Pie charts are useful in displaying relative proportions of data in a particular category. Below is an example of plotting a pie chart using the PyPlot module and assigning custom colors.

import matplotlib.pyplot as plt

# Data to plot

clubs = ["Club A", "Club B", "Club C", "Club D"]

percentages = [30, 20, 25, 25]

colors = ["#F4D03F", "#FE642E", "#2EFE2E", "#1C4686"]

# Plotting Pie Chart

plt.pie(percentages, labels=clubs, colors=colors, autopct='%1.1f%%', startangle=90)

# Adding title to plot

plt.title("Pie Chart Example")

# Display Plot

plt.show()

In the above example, the pie() function is used to create a pie chart. The percentages of each club are assigned to a list, clubs is a list of the names of the clubs, and colors are a list of different color codes assigned to the clubs.

The autopct keyword allows the display of percent on the pie chart, and the start angle specifies the starting point of the pie chart.

### Customizing Legends in Graphs

Customizing legends in graphs helps differentiate between datasets with multiple variables for data interpretation. The legend() function can be customized in multiple ways, labels, color, and anchoring methods.

In the below example, we will see how to create and customize the legend.

import matplotlib.pyplot as plt

import numpy as np

# X-axis values

x = np.linspace(0, 10, 50)

# Y-axis values

y1 = 2*x + 1

y2 = 3*x

# Plotting Multiple Lines

fig, ax = plt.subplots()

ax.plot(x, y1, label='Linear Equation Y=mx+c', color='red')

ax.plot(x, y2, label='Linear Equation Y=3x', color='blue')

# Customizing Legend

legend = ax.legend(loc='upper right')

frame = legend.get_frame()

frame.set_facecolor('white')

plt.show()

In the above example, we plot two linear equations, adding a custom label to the legend for each. The plot() function is modified to create a subplot with two different lines plotted with customized colors.

The legend is then customized using the loc parameter to place it at the upper-right corner of the plot, and boundaries and color are set using get_frame() and frame.set_facecolor() functions.

## Conclusion

This article covers beginners techniques for plotting line graphs, pie charts, and customizing legends in graphs. These easy-to-learn functions are vital in data analysis and interpretation.

As you continue to develop expertise in PyPlot module, it is essential to explore other advanced functionalities. In conclusion, PyPlot module in Python enables you to create data visualizations, representing complex and meaningful data sets through graphs and charts.

This article highlights the significance of customized legends, pie charts, and line graphs and their utility in data interpretation and representation. The PyPlot module offers simple and powerful functions, such as plot(), pie() and legend() functions, to generate these graphs, and customization options to create informative visuals for our data.

I hope this article has helped you learn more about the PyPlot module in Python and how to make comprehensive data visualizations using its functions.