Mathew K Analytics

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…

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.

📓 Full notebook

Download .ipynb

Data 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)
(32, 12)

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()
No description has been provided for this image
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()
No description has been provided for this image

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()
No description has been provided for this image
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()
No description has been provided for this image

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()
No description has been provided for this image

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()
No description has been provided for this image

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()
No description has been provided for this image

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.

  1. Which chart is best for showing how a single column like mpg is distributed?

  2. What does plt.scatter(df['wt'], df['mpg']) draw?

  3. How do you color scatter points by a third column such as cylinders?

  4. What does fig, axes = plt.subplots(1, 2, figsize=(10, 4)) create?

  5. Which call saves the current chart to a PNG file?

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. 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')
    
  2. 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')
    
  3. 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.