How to draw scatter plot using Matplotlib

Scatter plot drawn using Matplotlib
Scatter plot drawn using Matplotlib

Scatter plots are useful to show data points that lie in 2D. Drawing a scatter plot in Matplotlib is easy using the scatter function.

  • Assuming your data points are available as two NumPy arrays of shape (N, 1), drawing a scatter plot is straightforward:
import matplotlib.pyplot as mplot

# x_vals is NumPy array of shape (N, 1)
# y_vals is NumPy array of shape (N, 1)
mplot.scatter(x_vals, y_vals)
  • By default, markers that are filled discs, that is of type o, are drawn. This can changed to any of the other markers available in Matplotlib using the marker input argument. The different markers of Matplotlib are shown here.

  • The size of the marker is 20 by default. It can be changed by setting the s input argument.

  • The edge or border of the markers are drawn in black by default. If you do not want the edges to be drawn, then set the edgecolors input argument to none (a string, not the None value).

  • The color that is filled inside the marker is called the face color. It can be set by using the facecolors input argument. For setting the RGB values of N points, pass a NumPy array of shape (N, 3) where each color value lies in (0, 1).

  • If a dense set of data points is being drawn, multiple markers could obscure each other. This situation can be improved by adding some transparency to the markers. This can be set using the alpha input argument.

  • An example that uses all the above customizations to draw the figure shown above:

import matplotlib.pyplot as mplot

# x_vals is NumPy array of shape (N, 1)
# y_vals is NumPy array of shape (N, 1)
# c_arr  is NumPy array of shape (N, 3)

mplot.scatter(x_vals, y_vals, s=2, marker=".", facecolors=c_arr, edgecolors="none", alpha=0.5)

Tried with: Matplotlib 1.3.1 and Ubuntu 14.04

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s