How to Use Seaborn for Visualization in Python
Use
seaborn by first importing it with import seaborn as sns. Then, load or prepare your data and call functions like sns.scatterplot() or sns.barplot() to create charts. Finally, use plt.show() from matplotlib.pyplot to display the visualization.Syntax
Seaborn functions follow a simple pattern: you call a plotting function with your data and specify which columns to use for axes or categories. Most functions accept a data parameter for a DataFrame, and x and y parameters for the variables to plot.
Example parts:
sns.function_name(data=your_data, x='column1', y='column2'): creates the plotplt.show(): displays the plot window
python
import seaborn as sns import matplotlib.pyplot as plt sns.scatterplot(data=df, x='age', y='salary') plt.show()
Example
This example shows how to create a scatter plot using Seaborn with built-in sample data. It plots 'total_bill' against 'tip' from the 'tips' dataset.
python
import seaborn as sns import matplotlib.pyplot as plt # Load sample dataset tips = sns.load_dataset('tips') # Create scatter plot sns.scatterplot(data=tips, x='total_bill', y='tip') # Show the plot plt.show()
Output
A scatter plot window appears showing points representing total bill vs tip amounts.
Common Pitfalls
Common mistakes include:
- Not importing
matplotlib.pyplotand callingplt.show(), so the plot does not display. - Passing data in wrong format (Seaborn expects a DataFrame or similar).
- Using incorrect column names for
xoryparameters. - Forgetting to install Seaborn with
pip install seaborn.
python
import seaborn as sns # Wrong: no plt.show(), plot may not display sns.barplot(x=['A', 'B'], y=[5, 10]) # Right way: import matplotlib.pyplot as plt sns.barplot(x=['A', 'B'], y=[5, 10]) plt.show()
Quick Reference
| Function | Description | Common Parameters |
|---|---|---|
| sns.scatterplot() | Creates scatter plots | data, x, y, hue |
| sns.barplot() | Creates bar charts | data, x, y, hue, estimator |
| sns.lineplot() | Creates line charts | data, x, y, hue |
| sns.histplot() | Creates histograms | data, x, bins |
| sns.boxplot() | Creates box plots | data, x, y, hue |
Key Takeaways
Import seaborn as sns and matplotlib.pyplot as plt to start plotting.
Use seaborn plotting functions with data and specify x and y columns.
Always call plt.show() to display your plot window.
Seaborn works best with pandas DataFrames or similar data structures.
Check column names and data format to avoid common errors.