Matplotlib & Seaborn Visualization
Turn DataFrames into charts โ line, bar, histogram, and scatter with Matplotlib, then statistical plots with Seaborn.
Learning Objectives
- Create line, bar, histogram, and scatter plots with Matplotlib.
- Customize plots with titles, axis labels, and legends.
- Explain the difference between a bar chart and a histogram.
- Explain what Seaborn is and how it differs from Matplotlib.
- Use Seaborn for countplot, boxplot, and heatmap.
1. What Matplotlib Is
Matplotlib is Python's foundational data-visualization library. It gives you low-level control to build almost any chart, and Seaborn (and Pandas plotting) are built on top of it.
import matplotlib.pyplot as plt
2. The Four Core Plots
Line plot โ trend over time
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y)
plt.show()
Bar chart โ compare categories
plt.bar(["Pen", "Notebook", "Eraser"], [25, 120, 10])
plt.show()
Histogram โ distribution of a numeric variable
plt.hist(sales_data, bins=10)
plt.show()
Scatter plot โ relationship between two numbers
plt.scatter(price, units_sold)
plt.show()
3. Customizing Plots
plt.plot(x, y)
plt.title("Monthly Sales") # title
plt.xlabel("Month") # x-axis label
plt.ylabel("Sales (โน)") # y-axis label
plt.legend(["Sales"]) # legend
plt.show()
Clear titles, axis labels, and legends turn a bare chart into something a stakeholder can read.
4. Seaborn โ Statistical Plots
Seaborn is a library built on top of Matplotlib. It works directly with Pandas DataFrames and produces attractive statistical plots with far less code.
import seaborn as sns
# Countplot โ frequency of categories
sns.countplot(x="region", data=df)
# Boxplot โ distribution + outliers by category
sns.boxplot(x="region", y="sales", data=df)
# Heatmap โ correlation matrix
sns.heatmap(df.corr(), annot=True)
| Matplotlib | Seaborn | |
|---|---|---|
| Level | low-level, full control | high-level, built on Matplotlib |
| Data | lists/arrays | DataFrames directly |
| Look | plain by default | styled, statistical |
5. Interview Questions (with Model Answers)
The visualization questions interviewers ask. Self-test before revealing.
IQ1. What is Matplotlib, and why is it used?
Model answer: "Matplotlib is Python's foundational data-visualization library. It gives low-level control to build almost any chart, and it's the foundation Seaborn and Pandas plotting are built on."
IQ2. How do you create a basic line plot?
Model answer: "With plt.plot(x, y) followed by plt.show(). I can add
labels and a title with plt.xlabel(), plt.ylabel(), and plt.title()."
IQ3. How do you customize a plot?
Model answer: "With plt.title() for the title, plt.xlabel() and
plt.ylabel() for axis labels, and plt.legend() for the legend. These make a chart readable."
IQ4. What's the difference between a bar chart and a histogram?
Model answer: "A bar chart compares counts/values across distinct categories; a histogram shows the distribution of one numeric variable by binning it into ranges. Categories vs. continuous data."
IQ5. What's the difference between plt.plot and plt.scatter?
Model answer: "plot draws connected points (a line), best for trends over an ordered axis; scatter draws individual unconnected points, best for seeing the relationship between two numeric variables."
IQ6. What is Seaborn, and how does it differ from Matplotlib?
Model answer: "Seaborn is built on top of Matplotlib. It works directly with DataFrames and produces attractive statistical plots with less code, while Matplotlib is lower-level with more control."
IQ7. Which chart would you use to show a distribution of values?
Model answer: "A histogram โ it bins a numeric variable into ranges and shows frequency. For comparing distributions across groups, I'd use a Seaborn boxplot."
IQ8. What is a histogram used for?
Model answer: "To visualize the frequency distribution of a numeric variable โ how many values fall into each range/bin. It's a quick way to spot skew, outliers, and the overall shape of the data."
IQ9. How do you create a correlation heatmap in Seaborn?
Model answer: "sns.heatmap(df.corr(), annot=True) โ it computes the correlation matrix and
displays it as a colored grid, making relationships between numeric columns obvious."
Hands-On Project: Visualize a Sales Dataset
Using a sales DataFrame (region, product, sales, units), create the following plots.
Steps
- A line plot of monthly sales.
- A bar chart of sales by region.
- A histogram of the sales values.
- A scatter plot of price vs units sold.
- A Seaborn countplot of the region column.
View Solution / Walkthrough
import matplotlib.pyplot as plt
import seaborn as sns
# 1. Line plot
plt.plot(months, monthly_sales)
plt.title("Monthly Sales"); plt.show()
# 2. Bar chart by region
plt.bar(regions, sales_by_region)
plt.show()
# 3. Histogram
plt.hist(df["sales"], bins=10)
plt.show()
# 4. Scatter plot
plt.scatter(df["price"], df["units"])
plt.show()
# 5. Seaborn countplot
sns.countplot(x="region", data=df)
plt.show()
Key Takeaways
Matplotlib = low-level control; line/bar/histogram/scatter are the core four.
Always add title, axis labels, and a legend.
Bar chart = categories; histogram = distribution of one numeric variable.
Seaborn builds on Matplotlib, works with DataFrames, gives statistical plots.
countplot/boxplot/heatmap are the workhorse Seaborn charts.
Objective Questions โ Test Your Understanding
Q1. Which Matplotlib function creates a line plot?
Q2. Which Matplotlib function creates a bar chart?
Q3. Which Matplotlib function creates a histogram?
Q4. What is Seaborn?
Q5. Which Matplotlib function adds a title to a plot?