How to Create Scatter Plot with Seaborn in Python
To create a scatter plot in Python using
seaborn, use the sns.scatterplot() function by passing your data and specifying the x and y variables. This function plots points on a graph to show relationships between two numeric variables.Syntax
The basic syntax for creating a scatter plot with Seaborn is:
sns.scatterplot(x='x_column', y='y_column', data=dataframe): Plots points using columns from a DataFrame.x: The name of the column for the horizontal axis.y: The name of the column for the vertical axis.data: The DataFrame containing the data.
python
sns.scatterplot(x='x_column', y='y_column', data=dataframe)
Example
This example shows how to create a scatter plot using Seaborn with sample data. It plots the relationship between two numeric columns.
python
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # Sample data data = pd.DataFrame({ 'height': [150, 160, 170, 180, 190], 'weight': [50, 60, 65, 80, 90] }) # Create scatter plot sns.scatterplot(x='height', y='weight', data=data) # Show the plot plt.show()
Output
A scatter plot window showing points with height on the x-axis and weight on the y-axis.
Common Pitfalls
Common mistakes when creating scatter plots with Seaborn include:
- Not importing
seabornormatplotlib.pyplot, which are needed to plot and show the graph. - Passing incorrect column names or data types that are not numeric.
- Forgetting to call
plt.show()to display the plot in some environments.
Example of a wrong call and the correct way:
python
# Wrong: missing data argument or wrong column names # sns.scatterplot(x='wrong_x', y='wrong_y') # Correct: sns.scatterplot(x='height', y='weight', data=data)
Quick Reference
Here is a quick summary of key parameters for sns.scatterplot():
| Parameter | Description |
|---|---|
| x | Name of the column for x-axis values |
| y | Name of the column for y-axis values |
| data | DataFrame containing the data |
| hue | Column name for color grouping (optional) |
| style | Column name for marker style grouping (optional) |
| size | Column name for marker size grouping (optional) |
Key Takeaways
Use sns.scatterplot() with x, y, and data parameters to create scatter plots.
Ensure your data columns are numeric and correctly named.
Always import seaborn and matplotlib.pyplot before plotting.
Call plt.show() to display the plot when needed.
Use optional parameters like hue and style to add more information visually.