Scatter Plots
DS 2023 | Communicating with Data

Overview¶
A scatter plot uses dots to represent the values of two numeric measurement variables on a cartesian plane.
The domains of the two variables are mapped onto the x and y axes to generate a space.
Within this space, each dot on the plot represents an observation, i.e. a row of data.
Use Cases¶
Scatter plots can be used to identify relationships, trends, patterns, clusters, and outliers among the data points.
A common use case is to plot an independent variable (e.g. time) on the x-axis and a dependent variable on the y-axis.
Scatter plots allow you to visually assess how strongly two variables are correlated.
Frequently, scatter plots feature regression lines.
Like line graphs, the x and y axes of scatter plots are cropped. This is because the purpose of the plot is to show relationship, not magnitude.
Creating a scatter plot from scratch¶
To understand the design and purpose of a scatter plot, let’s build one from scratch.
We’ll create one out of some random numeric data.
We use NumPy’s random number generator that samples from the normal distribution to create a data frame with 1000 observations of 2 features.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsdf = pd.DataFrame({
'f1': np.random.randn(1000),
'f2': np.random.randn(1000)
})
df.head()To understand the logic of a scatter plot, consider how we’d create one by hand.
# Create figure and axes objects
fig, ax = plt.subplots()
# Scale the axes
ax.set_xlim(left=df.f1.min(), right=df.f1.max())
ax.set_ylim(bottom=df.f2.min(), top=df.f2.max())
# Plot each point
for idx, row in df.iterrows():
plt.plot(row.f1, row.f2, '.', c='tab:blue')
Pandas’ .plot.scatter() method does this for us.
df.plot.scatter(x='f1', y='f2')
plt.show()
Because both features are drawn from the normal distribution, they should exhibit no correlation.
Indeed, the result is a random blob of points that cluster around 0, the mean.
A better example¶
Let’s look at a better example, one involve real data.
We import the Palmer Penguins data set from Seaborn.
This dataset represents body-size measurements for 344 penguins of three species observed on three islands of the Palmer Archipelago, Antarctica.
penguins = sns.load_dataset('penguins').dropna()
penguinsHere is a scatter plot of two features.
penguins.plot.scatter(x='bill_length_mm', y='bill_depth_mm')
plt.show()
Note that the plot effectively zooms in one the data by cropping the axes.
If the axes are not cropped, you get like this:
penguins.plot.scatter(x='bill_length_mm', y='bill_depth_mm', xlim=(0, None), ylim=(0, None))
plt.show()
Showing a grouping variable with color¶
If you want to map the distribution of species onto the figure, you can associate color with the variable.
penguins.plot.scatter(x='bill_length_mm', y='bill_depth_mm', c='species')
plt.show()
The result shows that the observations cluster in the space created by the features.
This indicates that the features may be predictive of species.
Showing a third variable with size¶
We might also choose to change the size of each data point in proportion to a numeric variable.
Here we invent a feature size_factor to display for demonstration purposes.
We could have just used body_mass_g, but this results in very large circles.
penguins['size_factor'] = (penguins.body_mass_g - penguins.body_mass_g.min())/10penguins.plot.scatter(
x='bill_length_mm',
y='bill_depth_mm',
s='size_factor',
alpha=.25)
plt.show()
Showing variables with color and size¶
It’s actually pretty easy to show four variables in a scatter plot.
Here we use both color and size as channels on which to map a categorical and numeric feature respectively.
Here we bump up the size of the figure to make clearly visible all four variables.
penguins.plot.scatter(
x='bill_length_mm',
y='bill_depth_mm',
c='species',
s='size_factor',
alpha=.25,
figsize=(12, 10)
)
plt.show()
Viewing many scatter plots at once¶
Often when you have a bunch of measurement variables you will want to do a pairwise comparison of them all.
One quick way to do that is with a scatter matrix (also called a lattice).
Pandas provides this kind of plot through its plotting module.
ax = pd.plotting.scatter_matrix(penguins, figsize=(10,10))
Note that the function returns a two-dimensional array of Axes objects.
axarray([[<Axes: xlabel='bill_length_mm', ylabel='bill_length_mm'>,
<Axes: xlabel='bill_depth_mm', ylabel='bill_length_mm'>,
<Axes: xlabel='flipper_length_mm', ylabel='bill_length_mm'>,
<Axes: xlabel='body_mass_g', ylabel='bill_length_mm'>,
<Axes: xlabel='size_factor', ylabel='bill_length_mm'>],
[<Axes: xlabel='bill_length_mm', ylabel='bill_depth_mm'>,
<Axes: xlabel='bill_depth_mm', ylabel='bill_depth_mm'>,
<Axes: xlabel='flipper_length_mm', ylabel='bill_depth_mm'>,
<Axes: xlabel='body_mass_g', ylabel='bill_depth_mm'>,
<Axes: xlabel='size_factor', ylabel='bill_depth_mm'>],
[<Axes: xlabel='bill_length_mm', ylabel='flipper_length_mm'>,
<Axes: xlabel='bill_depth_mm', ylabel='flipper_length_mm'>,
<Axes: xlabel='flipper_length_mm', ylabel='flipper_length_mm'>,
<Axes: xlabel='body_mass_g', ylabel='flipper_length_mm'>,
<Axes: xlabel='size_factor', ylabel='flipper_length_mm'>],
[<Axes: xlabel='bill_length_mm', ylabel='body_mass_g'>,
<Axes: xlabel='bill_depth_mm', ylabel='body_mass_g'>,
<Axes: xlabel='flipper_length_mm', ylabel='body_mass_g'>,
<Axes: xlabel='body_mass_g', ylabel='body_mass_g'>,
<Axes: xlabel='size_factor', ylabel='body_mass_g'>],
[<Axes: xlabel='bill_length_mm', ylabel='size_factor'>,
<Axes: xlabel='bill_depth_mm', ylabel='size_factor'>,
<Axes: xlabel='flipper_length_mm', ylabel='size_factor'>,
<Axes: xlabel='body_mass_g', ylabel='size_factor'>,
<Axes: xlabel='size_factor', ylabel='size_factor'>]], dtype=object)Looking at correlation¶
One of the use cases of a scatter plot is that it can give us insight into the amount of correlation two variables have.
penguins.columnsIndex(['species', 'island', 'bill_length_mm', 'bill_depth_mm',
'flipper_length_mm', 'body_mass_g', 'sex', 'size_factor'],
dtype='str')measure_cols = ['bill_length_mm', 'bill_depth_mm',
'flipper_length_mm', 'body_mass_g']penguins[measure_cols].corr().style.background_gradient(axis=None, cmap="Spectral")Another example: Regression¶
Scatter plots are often used to show regression — the best estimate of a linear function to account for the relationship between x and y.
Let’s look at an example using Seaborn’s tips dataset.
This dataset represents the tips recorded by one waiter over a few months at a single restaurant in New York City, with the bill total and attributes of each dining party.
tips = sns.load_dataset("tips")
tips.head()Let’s add an analytical column showing the tip as a percentage of the total bill.
tips['tip_pct'] = tips.tip / tips.total_bill
tips.head()Except for a few outliers, it looks like tip as a percent remains about constant.
ax = tips.plot.scatter(x='total_bill', y='tip_pct', style='.', alpha=.5)
ax.axhline(tips['tip_pct'].median(), ls='--', c='tab:green')
plt.show()
If we want to fit a function to predict the tip from the total_bill , we can use NumPy’s polyfit function.
This returns and for the function:
where and are supplied by the two variables in question.
m, b = np.polyfit(x=tips.total_bill, y=tips.tip, deg=1)
tips['y_hat'] = tips.total_bill * m + b
print(f"Slope: {round(m,3)}, Intercept: {round(b,3)}")Slope: 0.105, Intercept: 0.92
So, to predict the tip of customer with a bill of (for this waiter at this restaurant), you could use this formula:
Here’s what that function looks like, plotted over the data.
tips.head()ax = tips.plot.scatter(x='total_bill', y='tip', alpha=0.5)
tips.plot.line(x='total_bill', y='y_hat', ax=ax, c='tab:orange', legend=False)
plt.show()
What if we want to show the difference between observation by category in the plot?
Here we color each point by its sex.
tips['sex'] = tips['sex'].astype('str')
tips.plot.scatter(x="total_bill", y="tip", c="sex", alpha=.5)
plt.show()
If we wanted to plot independent regression lines for each group, we could compute them independently and plot them on the same axes object.
tips_by_males = tips.query("sex == 'Male'")
m_male, b_male = np.polyfit(x=tips_by_males.total_bill, y=tips_by_males.tip, deg=1)
tips['y_hat_male'] = tips.total_bill * m_male + b_male
tips_by_females = tips.query("sex == 'Female'")
m_female, b_female = np.polyfit(x=tips_by_females.total_bill, y=tips_by_females.tip, deg=1)
tips['y_hat_female'] = tips.total_bill * m_female + b_femaletips.head()ax = tips.plot.scatter(x='total_bill', y='tip', alpha=0.5, c='sex')
tips.plot.line(x='total_bill', y='y_hat_male', ax=ax, legend=True)
tips.plot.line(x='total_bill', y='y_hat_female', ax=ax, legend=True)
plt.show()
We can see that in this sample males tip slightly more than females.
This is consistent with the median values for each group:
tips.groupby('sex').tip.median()sex
Female 2.75
Male 3.00
Name: tip, dtype: float64The colors in the above plot are mismatched.
We’d like to have the lines and dots match color for each group.
Here’s a way to achieve that goal.
fig, ax = plt.subplots()
colors = {
'Male': 'tab:blue',
'Female': 'tab:orange'
}
# Loop through each group to plot its scatter and regression line
for group_name, group_data in tips.groupby("sex", observed=False):
group_data.plot.scatter(x='total_bill', y='tip', ax=ax, c=colors[group_name], label=group_name)
yhat_col = f"y_hat_{group_name.lower()}"
group_data.plot.line(x='total_bill', y=yhat_col, ax=ax, legend=True, c=colors[group_name])
plt.show()
Anscombe’s Quartet¶
To conclude, let’s create scatter plots for Anscombe’s Quartet.
All four of these data sets have the same summary statistics.
anscombe = sns.load_dataset('anscombe')
anscombeLet’s define a convenient regression function.
def compute_regression(x, y):
m, b = np.polyfit(x, y, 1)
return x * m + bAnd now let’s plot them in a grid.
fig, ax = plt.subplots(2, 2, figsize=(8, 6), sharex=True, sharey=True)
# Define the location of each group in the 2D list of axes objects
# Note we could compute these from the iteration number
ax_loc = {
'I': [0,0],
'II': [0,1],
'III': [1,0],
'IV': [1,1],
}
for ds_name, ds in anscombe.groupby('dataset'):
r, c = ax_loc[ds_name]
my_ax = ax[r, c]
ds.plot.scatter(ax=my_ax, x='x', y='y', title=f"Dataset {ds_name}", s=40)
ds['y_hat'] = compute_regression(ds.x, ds.y)
ds.plot.line(ax=my_ax, x='x', y='y_hat', color='red', legend=False)
plt.tight_layout()
plt.show()