0
0
Matplotlibdata~15 mins

Figure size and DPI in Matplotlib - Deep Dive

Choose your learning style9 modes available
Overview - Figure size and DPI
What is it?
Figure size and DPI control how big and clear a plot looks in matplotlib. Figure size sets the width and height of the plot in inches. DPI, or dots per inch, controls how many pixels fit into each inch, affecting the sharpness. Together, they decide the final image size and quality you see or save.
Why it matters
Without understanding figure size and DPI, your plots might look blurry, too small, or too large when shown or saved. This can make data hard to read or look unprofessional. Knowing these lets you create clear visuals that fit perfectly in reports, presentations, or websites.
Where it fits
Before this, you should know basic matplotlib plotting commands. After this, you can learn about customizing plot styles, saving figures in different formats, and optimizing visuals for different devices or print.
Mental Model
Core Idea
Figure size sets the plot's physical dimensions, and DPI controls how many pixels fill each inch, together defining the plot's clarity and size.
Think of it like...
It's like printing a photo: figure size is the paper size, and DPI is the printer's resolution. A bigger paper with low resolution looks blurry, while a small paper with high resolution looks sharp.
┌───────────────────────────────┐
│          Figure Size           │  ← width x height in inches
│  ┌─────────────────────────┐  │
│  │                         │  │
│  │       Plot Area          │  │
│  │                         │  │
│  └─────────────────────────┘  │
│                               │
│ DPI (dots per inch) → Pixels per inch inside the figure
└───────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Figure Size Basics
🤔
Concept: Figure size defines the width and height of the plot in inches.
In matplotlib, you set figure size using plt.figure(figsize=(width, height)). For example, figsize=(6,4) creates a 6-inch wide and 4-inch tall plot. This controls how much space the plot takes on screen or paper.
Result
A plot with the specified physical size appears, larger or smaller depending on the inches set.
Understanding figure size helps you control the physical space your plot occupies, which is key for fitting visuals into layouts.
2
FoundationWhat DPI Means in Plots
🤔
Concept: DPI controls how many pixels fit into each inch of the figure, affecting sharpness.
DPI stands for dots per inch. A higher DPI means more pixels per inch, making the image sharper. You can set it in plt.figure(dpi=number). For example, dpi=100 means 100 pixels per inch.
Result
The plot appears sharper or blurrier depending on the DPI value.
Knowing DPI lets you adjust image clarity, which is crucial for printing or detailed displays.
3
IntermediateCombining Figure Size and DPI
🤔Before reading on: Do you think increasing DPI alone makes the plot bigger or just sharper? Commit to your answer.
Concept: Figure size and DPI together determine the total pixel dimensions of the plot.
The total pixel size = figure width (inches) × DPI by figure height (inches) × DPI. For example, a 6x4 inch figure at 100 DPI is 600x400 pixels. Changing DPI changes pixel count, not physical size on screen.
Result
You get control over both the physical size and pixel resolution of your plot.
Understanding this relationship helps you create images that look good on different screens or print sizes without distortion.
4
IntermediateSetting Figure Size and DPI When Saving
🤔Before reading on: Does saving a figure with higher DPI always increase its file size? Commit to your answer.
Concept: You can set DPI when saving a figure to control output quality independently from display size.
Use plt.savefig('file.png', dpi=300) to save a high-resolution image. This DPI affects the saved file's pixel density, making it sharper for print or zooming, even if the displayed figure was lower DPI.
Result
Saved images have the desired resolution and clarity for their use case.
Knowing how to set DPI on saving prevents blurry prints and ensures professional-quality visuals.
5
AdvancedHow DPI Affects Interactive Displays
🤔Before reading on: Do you think changing DPI affects how big the plot looks on your screen? Commit to your answer.
Concept: DPI influences pixel density but not the physical size on screen in interactive environments.
In interactive windows, figure size controls the window size, but DPI controls pixel density inside it. High DPI means more pixels packed in the same space, making lines and text sharper but not bigger.
Result
Plots look sharper but keep the same size on screen when DPI changes.
Understanding this prevents confusion when plots look the same size but differ in clarity.
6
ExpertInternal DPI and Backend Rendering
🤔Before reading on: Do you think all matplotlib backends handle DPI the same way? Commit to your answer.
Concept: Different matplotlib backends interpret DPI and figure size differently, affecting rendering.
Matplotlib uses various backends (like Agg, TkAgg, Qt5Agg). Some backends scale DPI differently or ignore it for display but respect it when saving. This can cause discrepancies between on-screen and saved image quality.
Result
Knowing backend behavior helps debug unexpected plot sizes or blurriness.
Understanding backend differences is key for consistent visuals across platforms and output formats.
Under the Hood
Matplotlib creates a figure canvas with a physical size in inches. DPI sets how many pixels fill each inch on this canvas. Internally, the canvas is a pixel grid sized by figure size × DPI. When rendering, matplotlib draws plot elements onto this pixel grid. Different backends then display or save this pixel grid, sometimes scaling it further depending on system settings.
Why designed this way?
This design separates physical size from pixel density, allowing flexible control over display and print quality. It matches real-world printing concepts and adapts to diverse output devices. Alternatives like fixed pixel sizes would limit adaptability and cause poor scaling on high-resolution screens or prints.
┌───────────────┐
│ Figure Size   │  (inches)
│  Width x Height│
└──────┬────────┘
       │ multiplied by
       ▼
┌───────────────┐
│ DPI (pixels/inch) │
└──────┬────────┘
       │ multiplied by
       ▼
┌─────────────────────┐
│ Pixel Dimensions     │
│ Width_px x Height_px │
└─────────┬───────────┘
          │ rendered by
          ▼
┌─────────────────────┐
│ Backend Renderer     │
│ (screen or file)     │
└─────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does increasing DPI always make the plot physically bigger on screen? Commit yes or no.
Common Belief:Higher DPI makes the plot bigger on screen.
Tap to reveal reality
Reality:Higher DPI increases pixel density, making the plot sharper but not physically larger on screen.
Why it matters:Misunderstanding this leads to confusion when plots look the same size but have different clarity.
Quick: If you set figure size to (6,4) and DPI to 100, is the saved image always 600x400 pixels? Commit yes or no.
Common Belief:The saved image size is always figure size times DPI.
Tap to reveal reality
Reality:The saved image size depends on the DPI set during saving, which can differ from the figure's DPI.
Why it matters:Ignoring save DPI causes unexpected image resolutions, affecting print quality.
Quick: Does changing DPI affect the amount of data shown in the plot? Commit yes or no.
Common Belief:Changing DPI changes how much data or plot content is visible.
Tap to reveal reality
Reality:DPI only affects pixel density, not the data range or plot content shown.
Why it matters:Confusing DPI with data scaling leads to wrong assumptions about plot zoom or detail.
Quick: Do all matplotlib backends handle DPI the same way? Commit yes or no.
Common Belief:All backends treat DPI identically.
Tap to reveal reality
Reality:Backends differ in DPI handling, causing variations in display and saved output.
Why it matters:Not knowing this causes inconsistent visuals across platforms and output formats.
Expert Zone
1
Some backends ignore figure DPI for display but respect it when saving, causing on-screen and saved image differences.
2
High DPI settings increase memory and file size significantly, which can slow down rendering or storage.
3
Matplotlib's default DPI varies by backend and environment, so explicit DPI setting avoids surprises.
When NOT to use
Avoid relying solely on DPI for plot clarity when targeting vector formats like SVG or PDF, which scale without pixelation. Instead, adjust figure size and font sizes directly. Also, for web display, consider CSS scaling rather than high DPI images to optimize performance.
Production Patterns
Professionals set figure size and DPI explicitly before saving plots for reports or publications to ensure consistent quality. They often use high DPI (300+) for print-ready images and lower DPI for quick screen previews. Automated scripts adjust these parameters based on output medium.
Connections
Raster vs Vector Graphics
Figure size and DPI control raster image resolution, while vector graphics scale without DPI.
Understanding DPI clarifies why raster images can blur when resized, unlike vector images that stay sharp.
Printing Technology
DPI in matplotlib mirrors printer DPI, linking digital plots to physical print quality.
Knowing printing DPI standards helps create plots that look good on paper, bridging digital and physical media.
Human Visual Acuity
DPI settings relate to how humans perceive sharpness and detail at different viewing distances.
Adjusting DPI with human vision in mind ensures plots are readable and comfortable to view.
Common Pitfalls
#1Plot looks blurry when saved at default DPI.
Wrong approach:plt.figure(figsize=(6,4)) plt.plot([1,2,3],[4,5,6]) plt.savefig('plot.png') # no dpi set
Correct approach:plt.figure(figsize=(6,4)) plt.plot([1,2,3],[4,5,6]) plt.savefig('plot.png', dpi=300)
Root cause:Not setting DPI on save uses default low DPI, causing low-resolution output.
#2Changing DPI to make plot bigger on screen.
Wrong approach:plt.figure(figsize=(6,4), dpi=200) plt.show() # expects bigger window
Correct approach:plt.figure(figsize=(12,8), dpi=100) plt.show() # bigger window by size, not DPI
Root cause:Confusing DPI with physical size; DPI affects sharpness, not window size.
#3Assuming saved image size equals figure size times figure DPI.
Wrong approach:plt.figure(figsize=(6,4), dpi=100) plt.savefig('plot.png') # expects 600x400 px image
Correct approach:plt.figure(figsize=(6,4), dpi=100) plt.savefig('plot.png', dpi=100) # explicit save DPI matches expectation
Root cause:Save DPI defaults can differ from figure DPI, causing unexpected image dimensions.
Key Takeaways
Figure size sets the physical dimensions of your plot in inches, controlling how much space it occupies.
DPI controls the pixel density inside the figure, affecting sharpness but not physical size on screen.
The total pixel size of a plot equals figure size multiplied by DPI, determining image resolution.
Setting DPI explicitly when saving ensures your output images have the desired clarity and size.
Different matplotlib backends handle DPI differently, so knowing this helps maintain consistent visuals.