In this tutorial, you'll learn how to create advanced scatter plots.

Set up the notebook

As always, we begin by setting up the coding environment. (This code is hidden, but you can un-hide it by clicking on the "Code" button immediately below this text, on the right.)

Load and examine the data

We'll work with a (synthetic) dataset of insurance charges, to see if we can understand why some customers pay more than others.

tut3_insurance

If you like, you can read more about the dataset here.

As always, we check that the dataset loaded properly by printing the first five rows.

Scatter plots

To create a simple scatter plot, we use the sns.scatterplot command and specify the values for:

The scatterplot above suggests that body mass index (BMI) and insurance charges are positively correlated, where customers with higher BMI typically also tend to pay more in insurance costs. (This pattern makes sense, since high BMI is typically associated with higher risk of chronic disease.)

To double-check the strength of this relationship, you might like to add a regression line, or the line that best fits the data. We do this by changing the command to sns.regplot.

Color-coded scatter plots

We can use scatter plots to display the relationships between (not two, but...) three variables! One way of doing this is by color-coding the points.

For instance, to understand how smoking affects the relationship between BMI and insurance costs, we can color-code the points by 'smoker', and plot the other two columns ('bmi', 'charges') on the axes.

This scatter plot shows that while nonsmokers to tend to pay slightly more with increasing BMI, smokers pay MUCH more.

To further emphasize this fact, we can use the sns.lmplot command to add two regression lines, corresponding to smokers and nonsmokers. (You'll notice that the regression line for smokers has a much steeper slope, relative to the line for nonsmokers!)

The sns.lmplot command above works slightly differently than the commands you have learned about so far:

Finally, there's one more plot that you'll learn about, that might look slightly different from how you're used to seeing scatter plots. Usually, we use scatter plots to highlight the relationship between two continuous variables (like "bmi" and "charges"). However, we can adapt the design of the scatter plot to feature a categorical variable (like "smoker") on one of the main axes. We'll refer to this plot type as a categorical scatter plot, and we build it with the sns.swarmplot command.

Among other things, this plot shows us that:

What's next?

Apply your new skills to solve a real-world scenario with a coding exercise!


Have questions or comments? Visit the Learn Discussion forum to chat with other Learners.