By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
A Hyper-Practical, Zero-Fluff Study Guide
You’re a data scientist at a retail company. Your boss drops a dataset on your desk: "Why are sales dropping in Q3? Is it pricing, seasonality, or something else?" You could stare at a spreadsheet for hours—or you could visualize distributions, relationships, and trends in 5 minutes and spot the pattern instantly.
This guide covers how to turn raw data into actionable insights using Python’s visualization libraries (matplotlib, seaborn, plotly). You’ll learn: - Distributions: Are sales normally distributed, or are there outliers skewing results? - Relationships: Does price correlate with demand? Is there a hidden interaction between marketing spend and revenue? - Time Series: Are sales declining, or is this just seasonal noise?
matplotlib
seaborn
plotly
Why this matters in production:- Debugging models: If your ML model performs poorly, visualizing feature distributions can reveal data leakage or skew.- Stakeholder communication: A well-designed plot can convince executives to act faster than a 50-page report.- Anomaly detection: Time-series visualizations help spot fraud, system failures, or unexpected trends before they become crises.
Real-world scenario:You inherit a legacy forecasting script that’s suddenly predicting negative sales. Instead of diving into the code, you plot the historical data and see a structural break (e.g., a new competitor entered the market). Now you know the model needs retraining—not debugging.
sns.histplot
plt.hist
Production insight: If your target variable is bimodal, your model might need stratification (e.g., separate models for high/low spenders).
Kernel Density Estimate (KDE) (sns.kdeplot)
sns.kdeplot
Production insight: KDEs reveal hidden clusters (e.g., two distinct customer segments in a single feature).
Boxplot (sns.boxplot)
sns.boxplot
Production insight: Outliers in a boxplot might indicate data entry errors or fraudulent transactions.
Violin Plot (sns.violinplot)
sns.violinplot
sns.scatterplot
plt.scatter
Production insight: A non-linear relationship (e.g., U-shaped) means linear regression will fail.
Line Plot (sns.lineplot, plt.plot)
sns.lineplot
plt.plot
Production insight: Overplotting (too many lines) can hide trends—use transparency (alpha) or aggregation.
alpha
Heatmap (sns.heatmap)
sns.heatmap
Production insight: A high correlation between features (e.g., age and birth_year) can cause multicollinearity in models.
age
birth_year
Pair Plot (sns.pairplot)
sns.pairplot
height_cm
height_inches
Production insight: Seasonality (e.g., higher sales in December) can be masked by noise—use rolling averages.
Autocorrelation Plot (ACF/PACF) (statsmodels.graphics.tsaplots.plot_acf)
statsmodels.graphics.tsaplots.plot_acf
Production insight: Helps determine lag order for ARIMA models.
Decomposition Plot (statsmodels.tsa.seasonal.seasonal_decompose)
statsmodels.tsa.seasonal.seasonal_decompose
pandas
statsmodels
bash pip install pandas matplotlib seaborn statsmodels
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from statsmodels.tsa.seasonal import seasonal_decompose # Load data df = pd.read_csv("retail_data.csv", parse_dates=["date"]) print(df.head()) # Check for missing values print(df.isnull().sum())
Expected output:
date region price sales 0 2022-01-01 North 19.99 150 1 2022-01-02 North 24.99 200 ...
sns.histplot(df["sales"], kde=True, bins=30) plt.title("Sales Distribution") plt.show()
What to look for:- Skewness: If sales are right-skewed, log-transform them for modeling.- Outliers: Extreme values might be data errors.
sns.boxplot(data=df, x="region", y="sales") plt.title("Sales by Region") plt.show()
What to look for:- Median differences: Are some regions underperforming? - Outliers: A single store might be skewing results.
sns.scatterplot(data=df, x="price", y="sales", hue="region", alpha=0.5) plt.title("Price vs. Sales by Region") plt.show()
What to look for:- Non-linear trends: If sales drop after a certain price, consider a piecewise model.- Heteroscedasticity: If variance increases with price, your model might need weighted regression.
corr = df[["price", "sales", "discount"]].corr() sns.heatmap(corr, annot=True, cmap="coolwarm") plt.title("Correlation Matrix") plt.show()
What to look for:- High correlation (e.g., price and discount): Might cause multicollinearity in regression.
price
discount
df.set_index("date", inplace=True) df["sales"].plot(figsize=(12, 6)) plt.title("Daily Sales Over Time") plt.show()
What to look for:- Trends: Is sales growing or declining? - Seasonality: Are there repeating patterns (e.g., weekly spikes)?
decomposition = seasonal_decompose(df["sales"].resample("D").mean(), model="additive", period=7) decomposition.plot() plt.show()
What to look for:- Trend: Long-term increase/decrease.- Seasonality: Weekly/yearly patterns.- Residuals: Random noise (if not random, your model is missing something).
os.environ
python-dotenv
python from dotenv import load_dotenv load_dotenv() API_KEY = os.getenv("API_KEY")
sns.relplot(kind="line")
python plt.savefig("sales_trend.png", dpi=300, bbox_inches="tight")
python sns.set_theme(style="whitegrid", palette="pastel")
python plt.xlabel("Price ($)") plt.ylabel("Sales (Units)") plt.title("Price Elasticity of Demand")
python import logging logging.basicConfig(filename="viz.log", level=logging.INFO) logging.info("Generated sales distribution plot")
plt.xscale("log")
alpha=0.1
sns.stripplot()
bins="auto"
sns.histplot(bins=50)
seasonal_decompose()
sales
DoWhy
✅ Scatter plot (not bar plot or histogram).
"How do you visualize a time series with daily seasonality?"
✅ Decomposition plot (trend + seasonality + residuals).
"What’s the difference between a histogram and a KDE?"
✅ KDE: Smooth probability density.
"How do you detect outliers in a dataset?"
"You’re analyzing customer churn. You have 10,000 rows of data with 50 features. Which visualization should you use to quickly spot patterns?" - ✅ Pair plot (for numerical features) + heatmap (for correlations).- ❌ 3D scatter plot (hard to interpret).
Challenge:You have a dataset of daily website traffic (date, visitors). Plot the data and answer: 1. Is there a weekly seasonality? 2. Are there any outliers (e.g., traffic spikes)?
date
visitors
Solution:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Load data df = pd.read_csv("traffic.csv", parse_dates=["date"]) df.set_index("date", inplace=True) # Plot df["visitors"].plot(figsize=(12, 6)) plt.title("Daily Website Traffic") plt.show() # Decompose from statsmodels.tsa.seasonal import seasonal_decompose decomposition = seasonal_decompose(df["visitors"], model="additive", period=7) decomposition.plot() plt.show()
Why it works:- The line plot shows trends/outliers.- The decomposition plot separates seasonality (e.g., higher traffic on weekends).
sns.histplot(data=df, x="sales")
kde=True
sns.boxplot(data=df, x="region", y="sales")
sns.scatterplot(data=df, x="price", y="sales")
hue="region"
df["sales"].plot()
resample("M").mean()
sns.heatmap(df.corr())
annot=True
seasonal_decompose(df["sales"], period=7)
model="additive"
"multiplicative"
sns.pairplot(df)
sns.kdeplot(data=df, x="sales")
shade=True
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.