Lesson 13 · Data analytics zero to hero
Data Visualisation with Matplotlib | Data Analytics #13
And the start of the visualization block: line plots, bar charts, histograms, and scatter plots. We're back to the real mtcars dataset, 1974 Motor Trend car…
- CourseData analytics zero to hero
- Lesson13 of 30
- Video10 min
- FormatJupyter notebook · 8 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- mtcars.csv preview1.7 KB
📓 Full notebook
Download .ipynbData Analytics Zero to Hero, Video 13: Data Visualization with Matplotlib#
- Video thirteen of the 30-part series, and the start of the visualization block: line plots, bar charts, histograms, and scatter plots.
- We're back to the real mtcars dataset, 1974 Motor Trend car road tests, this time to actually see the data.
- Let's jump straight in.
Before You Start#
- Open a new Jupyter Notebook in VS Code and select your Python interpreter as the kernel.
- Install Matplotlib if you haven't already:
pip install matplotlib. - Place mtcars.csv in the same folder as this notebook.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('mtcars.csv')
print(df.shape)
Part 1: Line Plots and Bar Charts#
sorted_df = df.sort_values('mpg').reset_index(drop=True)
plt.plot(sorted_df.index, sorted_df['mpg'])
plt.title('Real MPG Values, Sorted')
plt.xlabel('Car Rank')
plt.ylabel('MPG')
plt.show()
top5 = df.nlargest(5, 'mpg')
plt.bar(top5['model'], top5['mpg'], color='steelblue')
plt.title('Top 5 Most Fuel-Efficient Real Cars')
plt.ylabel('MPG')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.show()
Part 2: Scatter Plots#
plt.scatter(df['wt'], df['mpg'])
plt.title('Real Weight vs. MPG')
plt.xlabel('Weight (1000 lbs)')
plt.ylabel('MPG')
plt.show()
colors = df['cyl'].map({4: 'green', 6: 'orange', 8: 'red'})
plt.scatter(df['wt'], df['mpg'], c=colors)
plt.title('Real Weight vs. MPG, Colored by Cylinder Count')
plt.xlabel('Weight (1000 lbs)')
plt.ylabel('MPG')
plt.show()
Part 3: Histograms#
plt.hist(df['mpg'], bins=8, color='mediumseagreen', edgecolor='black')
plt.title('Distribution of Real MPG Values')
plt.xlabel('MPG')
plt.ylabel('Number of Cars')
plt.show()
Part 4: Subplots#
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].scatter(df['wt'], df['mpg'])
axes[0].set_title('Weight vs. MPG')
axes[1].hist(df['hp'], bins=8, color='coral')
axes[1].set_title('Horsepower Distribution')
plt.tight_layout()
plt.show()
Part 5: Saving a Figure#
plt.scatter(df['wt'], df['mpg'], c=colors)
plt.title('Real Weight vs. MPG, Colored by Cylinder Count')
plt.xlabel('Weight (1000 lbs)')
plt.ylabel('MPG')
plt.savefig('weight_vs_mpg.png', dpi=150, bbox_inches='tight')
plt.show()
Wrap-Up: What You Learned#
- Line plots and bar charts, with plot and bar.
- Scatter plots, including coloring points by a third categorical column.
- Histograms for visualizing a single column's distribution.
- Subplots, for comparing multiple charts in one figure.
- Saving a chart to a real image file with savefig.
- All of it built on the real mtcars dataset. Video fourteen covers Seaborn, a higher-level charting library built on top of Matplotlib, for faster, more polished statistical charts. Subscribe so it lands automatically see you there.
🧠 Test yourself
Pick an answer to check it. Your best score is saved in this browser.
Which chart is best for showing how a single column like mpg is distributed?
A histogram groups values into bins and shows how many fall in each, which reveals the shape of the distribution.
What does
plt.scatter(df['wt'], df['mpg'])draw?A scatter plot places one point per row, using the first argument for x and the second for y.
How do you color scatter points by a third column such as cylinders?
The
cargument accepts one color per point. Mapping cyl to color names gives a color per cylinder count.What does
fig, axes = plt.subplots(1, 2, figsize=(10, 4))create?subplots(rows, cols) makes a grid of axes. Here it is 1 row and 2 columns.
Which call saves the current chart to a PNG file?
plt.savefig writes the figure to a file. Call it before plt.show(), since show may clear the figure.
💻 Practice exercises
Try each one in the notebook or in your own editor before opening the solution.
Plot a line chart of the sorted values
[14.3, 18.1, 21.0, 22.8, 32.4]with a title and axis labels. Save to 'line.png'.💡 Hint
Use plt.plot, plt.title, plt.xlabel, plt.ylabel and plt.savefig.
✅ Show solution
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt mpg = [14.3, 18.1, 21.0, 22.8, 32.4] plt.plot(range(len(mpg)), mpg) plt.title('Sorted MPG') plt.xlabel('Car rank') plt.ylabel('MPG') plt.savefig('line.png')
Make a bar chart of 3 cars' mpg with a title and rotated x labels, using a tiny DataFrame.
💡 Hint
plt.bar(df['model'], df['mpg']) and plt.xticks(rotation=45, ha='right').
✅ Show solution
import matplotlib matplotlib.use('Agg') import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'model': ['Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'mpg': [32.4, 30.4, 33.9]}) plt.bar(df['model'], df['mpg'], color='steelblue') plt.title('Top fuel-efficient cars') plt.ylabel('MPG') plt.xticks(rotation=45, ha='right') plt.tight_layout() plt.savefig('bar.png')
Create a figure with two subplots: a scatter plot of wt vs mpg colored by cyl (mapping 4/6/8 to green/orange/red) and a histogram of hp. Use small inline data and save the figure.
💡 Hint
Use fig, axes = plt.subplots(1, 2) and axes[0].scatter(...), axes[1].hist(...).
✅ Show solution
import matplotlib matplotlib.use('Agg') import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({ 'wt': [2.6, 2.9, 3.4, 3.2, 1.8, 3.6], 'mpg': [21.0, 22.8, 18.7, 14.3, 32.4, 15.2], 'cyl': [6, 4, 8, 8, 4, 8], 'hp': [110, 93, 175, 245, 66, 150] }) colors = df['cyl'].map({4: 'green', 6: 'orange', 8: 'red'}) fig, axes = plt.subplots(1, 2, figsize=(10, 4)) axes[0].scatter(df['wt'], df['mpg'], c=colors) axes[0].set_title('Weight vs MPG') axes[1].hist(df['hp'], bins=4, color='coral', edgecolor='black') axes[1].set_title('Horsepower') plt.tight_layout() plt.savefig('subplots.png', dpi=150)
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



