5 Essential Matplotlib Tricks for Data Science 🚀

Published: 31 May 2025
on channel: CodeVisium
693
5

1. Create a simple line plot

Drawing a line plot is the foundation for visualizing trends over a continuous variable. In Matplotlib, you import the pyplot module and call plot() on your x–y arrays.

Long form

import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.figure(figsize=(6,4))
plt.plot(x, y, linestyle='-', marker='o')
plt.show()

One-liner

__import__('matplotlib.pyplot').pyplot.plot([0,1,2,3,4],[0,1,4,9,16],linestyle='-',marker='o'); __import__('matplotlib.pyplot').pyplot.show()

2. Customize plot labels and title

Adding axis labels and a title provides essential context for your viewers. Use xlabel(), ylabel(), and title() to annotate your figure.

Long form

import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.figure(figsize=(6,4))
plt.plot(x, y, color='green')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
plt.title('Square Numbers Line Plot')
plt.grid(True)
plt.show()

One-liner

__import__('matplotlib.pyplot').pyplot.plot([0,1,2,3,4],[0,1,4,9,16],color='green'); __import__('matplotlib.pyplot').pyplot.xlabel('X Axis Label'); __import__('matplotlib.pyplot').pyplot.ylabel('Y Axis Label'); __import__('matplotlib.pyplot').pyplot.title('Square Numbers Line Plot'); __import__('matplotlib.pyplot').pyplot.grid(True); __import__('matplotlib.pyplot').pyplot.show()

3. Create multiple subplots in one figure

Subplots let you display multiple related plots side by side. Use plt.subplots() to create a grid of axes, then call plotting functions on each axis.

Long form

import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
y1 = [0, 1, 4, 9, 16]
y2 = [16, 9, 4, 1, 0]
fig, axes = plt.subplots(1, 2, figsize=(10,4))
axes[0].plot(x, y1, color='blue')
axes[0].set_title('Ascending Squares')
axes[0].set_xlabel('X')
axes[0].set_ylabel('X²')
axes[1].plot(x, y2, color='red')
axes[1].set_title('Descending Squares')
axes[1].set_xlabel('X')
axes[1].set_ylabel('16−X²')
plt.tight_layout()
plt.show()

4. Generate a scatter plot with color mapping

Scatter plots visualize the relationship between two numeric variables, and adding a colormap based on a third variable reveals additional insight. Use scatter(x, y, c=values, cmap='viridis').

Long form

import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
c = x + y
plt.figure(figsize=(6,5))
plt.scatter(x, y, c=c, cmap='viridis', s=50, edgecolor='k')
plt.colorbar(label='x + y')
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('Scatter Plot with Color Mapping')
plt.show()

5. Plot a histogram with a density curve

Histograms show the distribution of a single variable, and overlaying a density curve (via kernel density estimate or a fitted distribution) helps visualize shape more smoothly.

Long form

import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(loc=0, scale=1, size=1000)
plt.figure(figsize=(6,4))
counts, bins, patches = plt.hist(data, bins=30, density=True, alpha=0.6, color='skyblue')
density = (1 / (np.sqrt(2 * np.pi) * 1)) * np.exp(- (bins**2) / 2)
plt.plot(bins, density, color='darkblue', linewidth=2)
plt.xlabel('Value')
plt.ylabel('Probability Density')
plt.title('Histogram with Normal Density Curve')
plt.show()

5 Interview Questions (with Answers):

1. Q: How do you change the figure size in Matplotlib, and why might you want to?

A: Use plt.figure(figsize=(width, height)) or fig, ax = plt.subplots(figsize=(w, h)). Larger dimensions improve readability, accommodate more subplots, and produce higher-resolution images for presentations or publication.

2. Q: What is the difference between plt.plot() and plt.scatter()?

A: plt.plot() draws a line (and optionally markers) connecting data points in sequence. plt.scatter() places individual markers at specified (x, y) coordinates without connecting lines and can map a third variable to color or marker size.

3. Q: How do you create a grid of subplots having 2 rows and 3 columns?

A: Call fig, axes = plt.subplots(2, 3, figsize=(width, height)). Here, axes is a 2×3 NumPy array of Axes objects. You can index axes[row, col] to plot on each subplot.

4. Q: How can you save a Matplotlib figure to disk without displaying it on-screen?

A: Replace plt.show() with plt.savefig('filename.png', dpi=300, bbox_inches='tight') to save the current figure at 300 DPI. Omitting show() keeps the GUI window from appearing.

5. Q: Describe how to add annotation text pointing to a data point in a plot.

A: Use plt.annotate(text, xy=(x_coord, y_coord), xytext=(x_text, y_text), arrowprops=dict(arrowstyle='-v')). This places text at xytext and draws an arrow from the text to the data point at xy.

#matplotlib #Python #DataScience #Visualization #CodingTips #Analytics #DeveloperShortcuts


On this page of the site you can watch the video online 5 Essential Matplotlib Tricks for Data Science 🚀 with a duration of hours minute second in good quality, which was uploaded by the user CodeVisium 31 May 2025, share the link with friends and acquaintances, this video has already been watched 693 times on youtube and it was liked by 5 viewers. Enjoy your viewing!