Data Visualization: lesson 2 of 3
Data Visualization
Matplotlib Fundamentals for Data Science
Create clear Python charts with Matplotlib and learn the building blocks behind figures and axes.
Concept
Matplotlib is a flexible Python plotting library. It provides the basic building blocks for many common Data Science charts and integrates naturally with NumPy and Pandas data. The website does not run this code; run it in a Python environment to generate the described plot.
Why It Matters
Charts are easier to trust and reuse when their labels, scales, and grouping are explicit in code. Matplotlib lets you turn an analysis question into a reproducible figure rather than manually editing a chart in a spreadsheet.
Intuition: Figure and Axes
Think of a figure as the whole canvas and an axes object as one plotting area on that canvas. The short plt style is useful for a quick plot. The object-oriented pattern, fig, ax = plt.subplots(), is often easier to extend because each chart is clearly attached to its own axes.
Line Chart: Monthly Sales
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [12000, 13800, 13100, 15400]
fig, ax = plt.subplots()
ax.plot(months, sales, marker="o", label="Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue ($)")
ax.set_title("Monthly Revenue")
ax.legend()
plt.show()
Expected Visual and Interpretation
Running this code produces a line chart with one point per month. The line makes the ordered trend visible: revenue rises from January to February, dips slightly in March, and reaches its highest shown value in April. It does not explain why revenue changed; check campaign timing, seasonality, and data quality before drawing a conclusion.
Code Explanation
plt.subplots() creates the figure and one axes. ax.plot() draws the line and markers. set_xlabel, set_ylabel, and set_title make the chart understandable outside the notebook. label and legend() identify the series, which becomes important when multiple lines are present. plt.show() displays the finished figure in a local Python environment.
Other Core Chart Types
regions = ["North", "South", "East", "West"]
revenue = [82000, 71000, 91000, 76000]
ages = [22, 28, 31, 31, 36, 42, 45, 52]
ad_spend = [100, 200, 300, 400]
sales_value = [1200, 1800, 2100, 2900]
plt.bar(regions, revenue)
plt.xlabel("Region")
plt.ylabel("Revenue ($)")
plt.title("Revenue by Region")
plt.show()
plt.hist(ages, bins=5)
plt.xlabel("Customer age")
plt.ylabel("Number of customers")
plt.title("Customer Age Distribution")
plt.show()
plt.scatter(ad_spend, sales_value)
plt.xlabel("Advertising spend ($)")
plt.ylabel("Sales ($)")
plt.title("Advertising Spend and Sales")
plt.show()
The bar chart compares regions, the histogram groups customer ages into bins to show their distribution, and the scatter plot places each paired spend/sales observation as a point. In a real analysis, inspect whether points represent comparable periods before treating a scatter pattern as meaningful.
Choosing the Right Approach
Use plt.plot() for ordered sequences, plt.bar() for category comparisons, plt.hist() for a numerical distribution, and plt.scatter() for two numerical variables. Prefer fig, ax when building multiple charts, adding annotations, or maintaining a reusable analysis notebook. The shorter plt functions are appropriate for small one-off examples.
Failure Signals
Common Mistakes
- Leaving default axis labels that do not state the metric or unit.
- Using a line chart for unordered regions or products.
- Adding a legend for a single obvious series, or omitting one for multiple series.
- Picking an arbitrary histogram bin count without checking whether it hides or exaggerates structure.
- Using decorative colors, 3D effects, or crowded annotations that distract from the question.
Best Practices
Name the figure around the question, label both axes, and keep units consistent. Use a readable scale and let the data determine whether a zero baseline is appropriate; bar charts generally need one. For several series, use distinguishable styles and a legend. Save the code that produces an important chart so the result can be reproduced after data updates.
Data Science Perspective
Matplotlib is often the base layer for inspection plots, model diagnostic charts, and presentation-ready custom figures. Many higher-level Python visualization tools build on or work alongside it. The most valuable skill is still interpreting what a plot can and cannot support.
Interview Perspective
Question: What is the benefit of fig, ax = plt.subplots()? Answer: it makes the figure and plotting area explicit, which is clearer when customizing or creating several charts. Follow-up: explain which chart you would use for a numerical distribution and why.
Practice Questions
- Write a
plt.bar()chart for three product categories and their revenue. - What labels would a scatter plot of customer age and monthly spend require?
- Why should a line chart not be used to compare unordered regions?
Quick Quiz
- What does
plt.show()do? Answer: displays the plot in a Python environment. - Which chart is appropriate for customer-age distribution? Answer: a histogram.
- What does an axes object represent? Answer: one plotting area within a figure.
Key Takeaway
Key Takeaways
Matplotlib creates reproducible charts with flexible building blocks. Use figures and axes to organize plots, choose a chart that matches the question, and make labels, scales, and legends support clear interpretation.
Next Lesson
Next, use Seaborn to create concise statistical visualizations from tabular data.
Finish this lesson on your terms
Mark it complete when you have worked through the material and are ready to move on.