Python / Data Science Essentials Interview Questions
How do you style Matplotlib figures and save them for reports?
The default Matplotlib style is functional but plain. For presentations and reports you need publication-quality output — chosen colour palettes, correct font sizes, no chart junk, and lossless or high-resolution raster output.
import matplotlib.pyplot as plt import numpy as np # --- Using a style sheet --- plt.style.use('seaborn-v0_8-whitegrid') # clean grid background # Other useful styles: 'ggplot', 'fivethirtyeight', 'bmh', 'dark_background' print(plt.style.available) # list all available styles # --- Common appearance tweaks via rcParams --- plt.rcParams.update({ 'font.size': 12, 'axes.labelsize': 13, 'axes.titlesize': 14, 'legend.fontsize': 11, 'figure.dpi': 100, 'lines.linewidth': 2, }) # --- Figure construction --- fig, ax = plt.subplots(figsize=(8, 5)) x = np.linspace(0, 10, 200) ax.plot(x, np.sin(x), color='#2E86AB', label='sin(x)') ax.fill_between(x, np.sin(x), 0, alpha=0.15, color='#2E86AB') ax.axhline(0, color='black', linewidth=0.8, linestyle='--') ax.set_title('Sine Wave with Fill', pad=12) ax.set_xlabel('x') ax.set_ylabel('sin(x)') ax.legend(loc='upper right') ax.spines[['top', 'right']].set_visible(False) # remove chart junk fig.tight_layout() # --- Saving --- fig.savefig('output.png', dpi=300, bbox_inches='tight') # raster fig.savefig('output.pdf', bbox_inches='tight') # vector fig.savefig('output.svg', bbox_inches='tight') # web/edit
Use bbox_inches='tight' whenever saving — it prevents axis labels being clipped at the edges. For publications use PDF or SVG (vector formats that scale without pixelation). For web and slides, PNG at 150–300 DPI is standard.
More Related questions...