how to plot scatter plot with python seaborn package

created at 07-01-2021 views: 5

seaborn is a package specially used for statistical data visualization, comparable to the ggplot2 package in R language. This article introduces the use of seaborn to draw scatter plots.

environments

  • python3.9
  • win10 64bit
  • seaborn==0.11.1
  • matplotlib==3.3.4
  • pandas==1.2.1

data

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# Settings
pd.options.display.notebook_repr_html=False # Table display
plt.rcParams['figure.dpi'] = 75 # resolution
sns.set_theme(style='darkgrid') # theme

load data

# change path to your own data path
tips=pd.read_csv(r'https://gitee.com/nicedouble/seaborn-data/raw/master/tips.csv') 
tips.head()
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3
3       23.68  3.31    Male     No  Sun  Dinner     2
4       24.59  3.61  Female     No  Sun  Dinner     4

plot

In seaborn, the functions for drawing scatter plots are scatterplot and relplot.
The easiest way for seaborn to draw a scatter plot is to use the scatterplot method, specifying the data parameter and the x and y parameters.

# Scatter chart
sns.scatterplot(data=tips,x='total_bill',y='tip')
plt.show()

plot

Add the hue parameter and set the group color of the points.

sns.scatterplot(data=tips,x='total_bill',y='tip',hue='time')
plt.show()

Add the hue parameter

Add the style parameter to set the grouping style of points.

sns.scatterplot(data=tips,x='total_bill',y='tip',style='sex')
plt.show()

Add the style parameter

Add the size parameter to set the grouping size of points.

sns.scatterplot(data=tips,x='total_bill',y='tip',size='size')
plt.show()

Add the size parameter

You can set multiple parameters of hue, style, and size at the same time:

sns.scatterplot(data=tips,x='total_bill',y='tip',hue='time',size='size')
plt.show()

set multiple parameters

The faceted scatter plot is drawn by the relplot method, you need to set kind="scatter", and then use the col, row parameters to facet.

faceted scatter plot

Please log in to leave a comment.