Scatter Plots with the plot Method
So far we’ve been only using line plots. But there’s a great variety of plots we can use in matplotlib. Let’s first talk about scatter plots. In this article we’ll see how to use the plt.plot method to graph scatter plots and in the next article we’ll use the plt.scatter method.
So, let’s jump in.
In scatter plots the points are not joined by segments. They are drawn individually as dots or other shapes.
Here’s an example of a line plot, to start with:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
If you pass a third argument to the plot method, you can easily create a scatter plot. Let it consist of circles:
fig, ax = plt.subplots()
ax.plot(x, y, 'o')
Here we passed ‘o’ as the argument, which is a circle marker. To better see the individual points, let’s cut down their number:
x = np.linspace(0, 10, 40)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, 'o')
There are lots of other markers available, let’s check out some of them:
# point marker
fig, ax = plt.subplots()
ax.plot(x, y, '.')
# pixel marker
fig, ax = plt.subplots()
ax.plot(x, y, ',')
# triangle_up marker
fig, ax = plt.subplots()
ax.plot(x, y, '^')
# tri_down marker
fig, ax = plt.subplots()
ax.plot(x, y, '1')
# square marker
fig, ax = plt.subplots()
ax.plot(x, y, 's')
# pentagon marker
fig, ax = plt.subplots()
ax.plot(x, y, 'p')
# plus marker
fig, ax = plt.subplots()
ax.plot(x, y, '+')
# x marker
fig, ax = plt.subplots()
ax.plot(x, y, 'x')
# diamond marker
fig, ax = plt.subplots()
ax.plot(x, y, 'D')
If you don’t like the color of the marker, you can combine the color symbol with the marker. For example, here’s how we can produce red square markers:
# red square marker
fig, ax = plt.subplots()
ax.plot(x, y, 'rs')
Using the plot method you can keep the line in addition to the markers. You just have to add a hyphen before the marker symbol or the color symbol:
# line + green diamond marker
fig, ax = plt.subplots()
ax.plot(x, y, '-gD')
You can pass some more arguments to the plot method to style the markers. Here are some examples:
# markersize
fig, ax = plt.subplots()
ax.plot(x, y, 'o', markersize=15)
# markerfacecolor and markeredgecolor
fig, ax = plt.subplots()
ax.plot(x, y, 'o', markersize=15, markerfacecolor='y', markeredgecolor='r')
# markeredgewidth
fig, ax = plt.subplots()
ax.plot(x, y, 'o', markersize=15, markerfacecolor='y', markeredgecolor='r', markeredgewidth=6)
There are lots of other options. Just check out the documentation to learn more.