top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

Scatter Plot Matplotlib

Scatter plots are powerful tools for visualizing relationships between two numerical variables. Matplotlib, a popular Python library, offers a variety of functions to create stunning scatter plots with ease. In this blog, we'll explore the wonders of scatter plots using Matplotlib, covering the basics, multiple scatter plots, subplots, and examples to illustrate their applications in real-life scenarios.

What is a Scatter Plot in Matplotlib?

Scatter plots are graphical representations that display individual data points as dots on a 2D plane. Each dot represents a unique combination of two variables, allowing us to identify patterns, correlations, or outliers within the data.

A scatter plot in Matplotlib can be created using the matplotlib.pyplot.scatter() function. Matplotlib plot refers to the general plotting capability provided by the Matplotlib library in Python. This function requires two arrays of the same length—one for the x-axis and the other for the y-axis values. It then plots points based on these coordinates.

Matplotlib-generated scatter plot:

Matplotlib line plot

"Matplotlib line plot" refers to the feature within the Matplotlib library that enables the creation of line plots, also known as line charts or line graphs. Line plots are a type of data visualization used to represent the relationship between two variables by connecting data points with straight lines. 

In Matplotlib, the plot() function generates line plots. This function allows you to provide x and y data points, specify line styles, colors, markers, and other visual attributes. 

Line plots are particularly useful for showing trends, changes, and patterns in data over a continuous range. They are commonly used in time series analysis, stock market data visualization, and other scenarios where the relationship between variables needs to be shown in a smooth and connected manner.

Using Matplotlib to Create Matplotlib scatter Plots

Scatter plot must be used in conjunction with the following library:

The following functions are necessary to create a scatter plot on a graph:

scatter() function's parameter

  • x-axis value: A list of x-axis data.

  • y-axis scale: A collection of y-axis data.

  • s: The size of the marker in points 2 c: The marker's color can be changed using a single variable or a list of variables.

  • marker: marker design

  • alpha: Adjusts the blending value of marker ranges between 0 and 1.

  • linewidths: Change the linewidths of the marker edges.

This example shows a basic scatter plot:

Output:

To create scatter plots using Matplotlib, you start by importing the necessary module. In this case, a scatter plot is generated to visualize data on a graph, where 'x' and 'y' represent lists of axis values. 

To achieve this, you can utilize the function 'matplotlib.pyplot.scatter()' or its shorthand 'plt.scatter()'. Once the plot is ready, the function 'matplotlib.pyplot.show()' or 'plt.show()' is employed to display the plot and make it visible to the user. 

This process allows for clear visualization and analysis of data relationships through scatter plots.

Showing the relationship between the number of pupils in each class as an example:

Example 1:

Output: 

To initiate a scatter plot showcasing the correlation between variables, start by importing the necessary module. 

The data for the x-axis is represented by the list "x," while the data for the y-axis is represented by the list "y." Enhance the visualization by specifying labels for both axes using the functions 'Matplotlib.pyplot.xlabel()' and 'Matplotlib.pyplot.ylabel()'. 

Customize the plot further by assigning a title using 'Matplotlib.pyplot.title()'. To control the x-axis intervals, employ 'Matplotlib.pyplot.xticks()', which accepts an array or list as an argument. The scatter plot itself is generated using 'Matplotlib.pyplot.scatter()', allowing you to effectively depict data relationships. 

To present the plot visually, utilize 'Matplotlib.pyplot.show()'. For additional intricacy in the scatter plot, the 'scatter()' function offers numerous parameters, including marker size, dot color, blending value, and linewidth. You can craft a scatter plot with detailed features by adjusting these parameters. 

This approach empowers you to visually analyze and understand data connections comprehensively.

Example 2:

Output:

Plotting Multiple Scatter Plots in Matplotlib

Plot multiple scatter plots in matplotlib has two methods.

  • Data is plotted in the same graph.

  • Making Use of Subplots Graphing data in many ways.

Plotting data in the same graph

Multiple scatter plots can be graphed on the same plot using various x and y-axis data by repeatedly executing the Matplotlib.pyplot.scatter() function.

Multiple scatter plots on the same graph, for example

# This code is written in python
# Importing required modules
import matplotlib.pyplot as plt
import numpy as np

# x and y values for the first scatter plot
x1  = [random.randint(0,50) for i in range(100)]
y1 = [random.randint(0,50) for i in range(100)]

# x and y values for the second scatter plot
x2  = [random.randint(0,50) for i in range(100)]
y2 = [random.randint(0,50) for i in range(100)]

# First Scatter plot
plt.scatter(x1, y1, c ="r",linewidths = 2, marker ="D", edgecolor ="b", s = 70, alpha=0.5)

#Second Scatter plot
plt.scatter(x2, y2, c ="k",linewidths = 2,marker ="p",edgecolor ="red",s = 150,alpha=0.5)

plt.title('Multiple Scatter plot')
plt.xlabel('x-axis')
plt.ylabel('y-axis')

plt.show()

Output: 

Let's break down the code step by step:

  • Importing Required Modules:

The code starts by importing the necessary modules for data visualization: matplotlib.pyplot (for creating plots) and numpy (for generating random data).

  • Generating Data:

The code generates random x and y values for two sets of data points. Each set contains 100 data points, and the x and y values are generated using the random.randint() function from the numpy library. These data points will be used for creating scatter plots.

  • Creating Scatter Plots:

The code proceeds to create two scatter plots using the plt.scatter() function. Each scatter plot is created by passing the corresponding x and y values. Various parameters are used to customize the appearance of the scatter plots:

  • c: Specifies the color of the markers.

  • linewidths: Sets the width of the marker outlines.

  • marker: Specifies the marker style used for the data points.

  • edgecolor: Sets the color of the marker edges.

  • s: Determines the size of the markers.

  • alpha: Controls the transparency of the markers.

  • Adding Titles and Labels:

The code adds a title, x-axis label, and y-axis label to the plot using the plt.title(), plt.xlabel(), and plt.ylabel() functions, respectively.

  • Displaying the Plot

The final step of the code is to display the created scatter plots using the plt.show() function.

Plotting multiple scatter plots using subplots

Matplotlib's subplots allow us to plot numerous graphs on the same figure. As a result, it can be used to create several scatter plots on the same graph. The subplot() function requires three arguments, the first two rows and columns for formatting the figure. The third argument represents the current plot's index.

Subplots are used to create multiple scatter plots.

# This code is written in python
import matplotlib.pyplot as plt
import numpy as np
import random 

plt.rcParams["figure.figsize"] = (10,6) 


plt.subplot(2,2,1)
x1=[random.randint(1,10) for i in range(50)]
y1=[random.randint(1,10) for i in range(50)]
plt.scatter(x1,y1,c='r')
plt.grid()


plt.subplot(2,2,2)
x2=[random.randint(1,10) for i in range(50)]
y2=[random.randint(1,10) for i in range(50)]
plt.scatter(x2,y2,c='g')
plt.grid()


plt.subplot(2,2,3)
x3=[random.randint(1,10) for i in range(50)]
y3=[random.randint(1,10) for i in range(50)]
plt.scatter(x3,y3,c='b')
plt.grid()


plt.subplot(2,2,4)
x4=[random.randint(1,10) for i in range(50)]
y4=[random.randint(1,10) for i in range(50)]
plt.scatter(x4,y4,c='y')
plt.grid()

Output:

The provided Python code uses the Matplotlib library to create a 2x2 grid of scatter plots, each containing randomly generated data points. The plt.rcParams["figure.figsize"] line sets the overall size of the figure. The code then creates four subplots within the grid, each displaying a scatter plot with 50 data points. 

For each subplot, two lists (x and y) are generated with random integer values between 1 and 10. The scatter plots in each subplot are colored differently using 'r' (red), 'g' (green), 'b' (blue), and 'y' (yellow). 

Matplotlib colors

"Matplotlib colors" refers to how you can specify and control colors when creating visualizations using the Matplotlib library in Python. Matplotlib offers various options for customizing the colors of different plot elements, such as data points, lines, bars, and more. 

Colors can be specified using different formats, including named colors (e.g., 'red', 'blue'), hexadecimal color codes (e.g., '#FF5733'), RGB tuples (e.g., (255, 87, 51)), and more. Additionally, Matplotlib provides access to a wide range of predefined color maps (matplotlib colormaps) that can be used to map continuous data values to colors. Customizing colors in Matplotlib allows you to enhance the visual appeal of your plots and convey information effectively by using color distinctions for various data points or categories.

Matplotlib scatter legend

This refers to the functionality within the Matplotlib library that enables the addition of a legend to scatter plots. A legend is a key that explains the meaning of the different elements in a plot, such as markers, colors, or line styles, allowing viewers to understand the data being presented. 

In the context of scatter plots, a legend can be used to clarify the significance of different marker styles or colors that represent various categories or data sets.

To add a legend to a scatter plot in Matplotlib, you typically use the legend() function after creating the scatter plot(s). The legend() function allows you to provide labels for the different elements in your plot and position the legend within the plot area. By providing labels corresponding to the categories or data sets in your scatter plot, you make it easier for viewers to interpret the plot and understand the relationships between the data points.

Matplotlib scatter marker styles

This refers to the various symbols or markers that can be used to represent individual data points in a scatter plot created using the Matplotlib library in Python. Scatter marker styles allow you to visually differentiate between different data points or categories within your plot. Matplotlib provides a wide range of marker styles that you can use to customize the appearance of data points, helping you convey more information in your visualizations.

You can specify marker styles using the marker parameter when calling the scatter() function in Matplotlib. Some common marker styles include circles, squares, triangles, and more. Additionally, Matplotlib offers variations of these basic shapes, allowing you to choose markers with different sizes, fill colors, and edge colors.

FAQs

  1. How can I customize the size of scatter plot markers in Matplotlib?

While the code example above covers some aspects of customization, adjusting the size of scatter plot markers can help emphasize data points. You can use the s parameter within the plt.scatter() function to control marker size. By providing a list of sizes corresponding to each data point, you can create scatter plots with variable marker sizes, enhancing the visual representation of your data.

  1. How can I add a color gradient to scatter plot markers based on a third variable?

If you have an additional variable that you want to represent using color gradients on your scatter plot, you can achieve this by using the c parameter along with a colormap. Specify the values of the third variable as the c parameter and provide a colormap using the cmap parameter. This will create a color gradient across your scatter plot, adding an extra layer of information to your visualization.

  1. How do I handle large datasets when creating scatter plots in Matplotlib?

While the provided code demonstrates scatter plots with randomly generated data, real-world datasets can be much larger. When dealing with large datasets, it's important to consider performance and readability. One approach is to use alpha blending (alpha parameter) to reduce the opacity of markers, making overlapping points more visible. Another strategy is to consider using subsampling or aggregation techniques to plot a representative sample of data points, maintaining the essence of the scatter plot while improving performance and readability.

Leave a Reply

Your email address will not be published. Required fields are marked *