Below are 50 practical Matplotlib questions and answers focusing on plotting, customization, and manipulation of figures and axes using Python's Matplotlib library.
Each question includes:
- A brief scenario
- A code snippet demonstrating one possible solution
Note: For all examples, assume you have imported Matplotlib as follows:
import matplotlib.pyplot as pltAnswer:
Use plt.plot() and plt.show() to display.
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.show()Answer:
Use plt.title("Your Title").
plt.plot([1,2,3],[2,4,6])
plt.title("My Line Plot")
plt.show()Answer:
Use plt.xlabel() and plt.ylabel().
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel("X-Axis Label")
plt.ylabel("Y-Axis Label")
plt.show()Answer:
Use plt.legend() after providing labels in plt.plot().
plt.plot([1,2,3],[2,4,6], label="Line 1")
plt.plot([1,2,3],[3,6,9], label="Line 2")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.show()Answer:
Use the linestyle parameter in plt.plot().
plt.plot([0,1,2],[0,1,4], linestyle='--', label="Dashed")
plt.legend()
plt.show()Answer:
Use the color parameter in plt.plot().
plt.plot([0,1,2],[0,1,4], color='red')
plt.show()Answer:
Call plt.plot() multiple times before plt.show().
plt.plot([1,2,3],[1,2,3], label="Line A")
plt.plot([1,2,3],[2,4,6], label="Line B")
plt.legend()
plt.show()Answer:
Use plt.scatter() with x and y values.
x = [1,2,3,4]
y = [10,8,12,15]
plt.scatter(x, y)
plt.show()Answer:
Use the marker parameter in plt.scatter().
plt.scatter([1,2,3],[2,3,4], marker='o')
plt.show()Answer:
Use plt.bar() for vertical bars.
categories = ['A','B','C']
values = [10,20,15]
plt.bar(categories, values)
plt.show()Answer:
Use plt.barh() for horizontal bars.
categories = ['A','B','C']
values = [10,20,15]
plt.barh(categories, values)
plt.show()Answer:
Use plt.errorbar() with yerr parameter.
x = [1,2,3]
y = [2,4,3]
yerr = [0.5, 0.2, 0.3]
plt.errorbar(x, y, yerr=yerr, fmt='o')
plt.show()Answer:
Use plt.hist() with your data.
data = [1,1,2,2,2,3,3,4,5]
plt.hist(data, bins=5)
plt.show()Answer:
Use plt.pie() with a list of values.
values = [30,40,20,10]
labels = ['A','B','C','D']
plt.pie(values, labels=labels)
plt.show()Answer:
Use plt.figure(figsize=(width,height)).
plt.figure(figsize=(8,4))
plt.plot([1,2,3],[2,4,1])
plt.show()Answer:
Use plt.savefig('filename.png') before plt.show().
plt.plot([1,2,3],[2,4,6])
plt.savefig('myplot.png')
plt.show()Answer:
Use plt.xlim() and plt.ylim().
plt.plot([1,2,3],[2,4,6])
plt.xlim(0,4)
plt.ylim(0,10)
plt.show()Answer:
Use plt.grid(True).
plt.plot([1,2,3],[2,4,6])
plt.grid(True)
plt.show()Answer:
Generate x values and compute y, then plot.
import numpy as np
x = np.linspace(-5,5,100)
y = x**2
plt.plot(x, y)
plt.show()Answer:
Use plt.text(x, y, "Text").
plt.plot([1,2],[2,4])
plt.text(1.5, 3, "Midpoint")
plt.show()Answer:
Use plt.subplot(rows, cols, index).
plt.subplot(1,2,1)
plt.plot([1,2],[2,4])
plt.subplot(1,2,2)
plt.plot([1,2],[3,1])
plt.show()Answer:
Use the sharex or sharey parameters in plt.subplots().
fig, (ax1, ax2) = plt.subplots(2,1, sharex=True)
ax1.plot([1,2,3],[2,4,6])
ax2.plot([1,2,3],[3,2,1])
plt.show()Answer:
Use plt.tight_layout() after creating subplots.
fig, (ax1, ax2) = plt.subplots(2,1)
ax1.plot([1,2],[2,4])
ax2.plot([1,2],[3,1])
plt.tight_layout()
plt.show()Answer:
Use plt.xticks() with desired labels.
x = [1,2,3]
y = [2,4,6]
plt.plot(x, y)
plt.xticks([1,2,3], ['One','Two','Three'])
plt.show()Answer:
Use plt.xticks(rotation=angle).
x = [1,2,3]
y = [2,4,6]
plt.plot(x, y)
plt.xticks([1,2,3], ['One','Two','Three'], rotation=45)
plt.show()Answer:
Use plt.xscale('log') or plt.yscale('log').
x = [1,10,100,1000]
y = [10,100,1000,10000]
plt.plot(x, y)
plt.xscale('log')
plt.yscale('log')
plt.show()Answer:
Use plt.gca().set_facecolor('color') or fig.set_facecolor().
fig = plt.figure()
fig.set_facecolor('lightgray')
plt.plot([1,2],[2,4])
plt.show()Answer:
Use linewidth parameter in plt.plot().
plt.plot([1,2],[2,4], linewidth=3)
plt.show()Answer:
Use plt.fill_between(x, y) where y is the function.
import numpy as np
x = np.linspace(0,1,50)
y = x**2
plt.plot(x, y)
plt.fill_between(x, y, color='yellow')
plt.show()Answer:
Use plt.annotate() with xy and xytext.
plt.plot([1,2,3],[2,4,3])
plt.annotate('Peak', xy=(2,4), xytext=(2,5), arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.show()Answer:
Use plt.figure(dpi=...).
plt.figure(dpi=150)
plt.plot([1,2,3],[2,4,6])
plt.show()Answer:
Use plt.clf() to clear the current figure.
plt.plot([1,2],[2,4])
plt.clf()
# Figure is now clearedAnswer:
Use plt.close() to close the current figure.
plt.plot([1,2],[2,4])
plt.show()
plt.close()Answer:
Use plt.axhline(y=value).
plt.axhline(y=0.5, color='red')
plt.show()Answer:
Use plt.axvline(x=value).
plt.axvline(x=2, color='green')
plt.show()Answer:
Use plt.axvspan(xmin, xmax, color='color').
plt.axvspan(1,2, color='grey', alpha=0.3)
plt.show()Answer:
Use ax2 = ax.twinx() on an existing Axes.
fig, ax = plt.subplots()
ax.plot([1,2,3],[2,4,6], color='blue')
ax2 = ax.twinx()
ax2.plot([1,2,3],[10,20,15], color='red')
plt.show()Answer:
Use ax2 = ax.twiny() on an existing Axes.
fig, ax = plt.subplots()
ax.plot([1,2,3],[2,4,6])
ax2 = ax.twiny()
ax2.set_xlim(ax.get_xlim())
plt.show()Answer:
Use ax.spines['top'].set_visible(False) and similarly for 'right'.
fig, ax = plt.subplots()
ax.plot([1,2,3],[2,4,3])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()Answer:
Use plt.subplot(projection='polar').
ax = plt.subplot(projection='polar')
theta = [0,0.5,1,1.5]
r = [1,2,1,3]
ax.plot(theta, r)
plt.show()Answer:
Use plt.colorbar() after plt.imshow() or similar functions.
import numpy as np
data = np.random.rand(10,10)
plt.imshow(data, cmap='viridis')
plt.colorbar()
plt.show()Answer:
Use a hex string like color='#FF5733'.
plt.plot([1,2],[2,4], color='#FF5733')
plt.show()Answer:
Use plt.xticks() or plt.yticks() with a custom list of tick positions.
plt.plot([1,2,3],[2,4,6])
plt.xticks([1,1.5,2,2.5,3])
plt.show()Answer:
Use plt.fill_between(x, y1, y2).
import numpy as np
x = np.linspace(0,1,50)
y1 = x
y2 = x**2
plt.plot(x, y1, x, y2)
plt.fill_between(x, y1, y2, where=(y1>y2), color='yellow', alpha=0.5)
plt.show()Answer:
Use the s parameter in plt.scatter().
x = [1,2,3,4]
y = [2,3,5,1]
sizes = [50,100,200,300]
plt.scatter(x, y, s=sizes)
plt.show()Answer:
Use subplots and plt.imshow() in each subplot.
import numpy as np
fig, axes = plt.subplots(1,2)
data1 = np.random.rand(10,10)
data2 = np.random.rand(10,10)
axes[0].imshow(data1, cmap='gray')
axes[1].imshow(data2, cmap='gray')
plt.show()Answer:
Use plt.tick_params() with labelrotation.
plt.plot([1,2,3],[2,4,6])
plt.tick_params(axis='x', labelrotation=90)
plt.show()Answer:
Use plt.contour() or plt.contourf() for filled contours.
import numpy as np
x = np.linspace(-2,2,50)
y = np.linspace(-2,2,50)
X,Y = np.meshgrid(x,y)
Z = X**2 + Y**2
plt.contour(X, Y, Z, levels=[1,2,3,4])
plt.show()Answer:
Set plt.xticks([]) and plt.yticks([]).
plt.plot([1,2],[2,4])
plt.xticks([])
plt.yticks([])
plt.show()Answer:
Convert dates to a suitable format and use plt.plot_date() or normal plt.plot() if x are datetimes.
import datetime as dt
dates = [dt.datetime(2021,1,1), dt.datetime(2021,1,2), dt.datetime(2021,1,3)]
values = [10,20,15]
plt.plot_date(dates, values, linestyle='-')
plt.show()If you found this helpful, consider following or starring the repository!
Stay updated with my latest content and projects!