Saving and Images

Back

Loading concept...

📸 Saving Your Matplotlib Masterpieces

The Photo Album Analogy

Imagine you just drew the most beautiful picture in the world. Now what? You want to save it so you can show your friends, print it, or put it on your wall!

Matplotlib figures are just like your drawings. After creating them, you need to save them to a file. Think of it like pressing the “Save” button in a drawing app on your tablet.


🎯 What You’ll Learn

  1. Save Figure Function – The magic button to save your chart
  2. Save File Formats – Different “flavors” of image files
  3. Save Options and DPI – Making your images sharp and crispy
  4. Image Loading – Bringing pictures INTO your charts
  5. Image Display Options – Making loaded images look great

1. The Save Figure Function – Your “Save” Button

The Story

Picture this: You’re an artist who just painted a sunset. You don’t want it to stay wet on the easel forever—you want to frame it and keep it safe!

In Matplotlib, savefig() is your “frame and save” button.

The Simple Way

import matplotlib.pyplot as plt

# Create your masterpiece
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("My First Saved Chart!")

# SAVE IT! 📸
plt.savefig("my_chart.png")

plt.show()

What happened? A file called my_chart.png appeared on your computer. That’s it!

Think of It Like This

Action Real Life Matplotlib
Draw something Paint on canvas plt.plot()
Save your work Frame the painting plt.savefig()
Show it off Hang on wall plt.show()

⚠️ Important Order!

ALWAYS save BEFORE show!

# ✅ CORRECT
plt.savefig("chart.png")
plt.show()

# ❌ WRONG (file will be blank!)
plt.show()
plt.savefig("chart.png")

Why? plt.show() clears the canvas. It’s like throwing away your painting after showing it!


2. Save File Formats – Pick Your Flavor

The Story

When you take a photo, your phone asks: JPEG? PNG? RAW? Each format has its superpower.

The Main Formats

graph TD A["Save Your Figure"] --> B{Which Format?} B --> C["PNG - Best Quality"] B --> D["JPG - Small Files"] B --> E["PDF - Perfect Print"] B --> F["SVG - Zoom Forever"]

Quick Comparison

Format Best For File Size Quality
PNG Web, presentations Medium Excellent
JPG Photos, web Small Good
PDF Printing, papers Small Perfect
SVG Websites, logos Tiny Infinite!

How to Use Each

# PNG - Crystal clear
plt.savefig("chart.png")

# JPG - For photos
plt.savefig("chart.jpg")

# PDF - Print quality
plt.savefig("chart.pdf")

# SVG - Scalable magic
plt.savefig("chart.svg")

Which One Should I Pick?

Ask yourself:

  • Showing on screen? → PNG
  • Printing on paper? → PDF
  • Making a website? → SVG
  • Need tiny file size? → JPG

3. Save Options and DPI – Making It SHARP

The Story

Ever zoomed into a photo and it got blurry? That’s because it didn’t have enough DPI (Dots Per Inch).

Think of DPI like tiny little dots. More dots = sharper image!

graph TD A["DPI = Dots Per Inch"] --> B["Low DPI 72"] A --> C["Medium DPI 150"] A --> D["High DPI 300"] B --> E["Blurry 😢"] C --> F["Clear 😊"] D --> G["Super Sharp! 🎯"]

Setting DPI

# Low quality (blurry)
plt.savefig("chart_72.png", dpi=72)

# Screen quality (good)
plt.savefig("chart_150.png", dpi=150)

# Print quality (crispy!)
plt.savefig("chart_300.png", dpi=300)

Other Useful Options

# Transparent background
plt.savefig("chart.png",
            transparent=True)

# Tight - no extra white space
plt.savefig("chart.png",
            bbox_inches='tight')

# White border padding
plt.savefig("chart.png",
            pad_inches=0.5)

# All together!
plt.savefig("perfect_chart.png",
            dpi=300,
            bbox_inches='tight',
            transparent=True)

Quick Reference

Option What It Does Example
dpi=300 Makes image sharper Print quality
transparent=True See-through background For overlays
bbox_inches='tight' Removes white space Clean edges
pad_inches=0.5 Adds border padding Breathing room

4. Image Loading – Bringing Pictures In

The Story

What if you want to add a photo to your chart? Like putting a picture of a cat on your graph (why not!).

Matplotlib can load images and treat them like data!

The Magic Function: imread()

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# Load an image
img = mpimg.imread("photo.png")

# Show it
plt.imshow(img)
plt.show()

What Can You Load?

graph TD A["imread can load"] --> B["PNG files"] A --> C["JPG files"] A --> D["Other images"] B --> E["✅ Recommended"] C --> F["✅ Works great"] D --> G["⚠️ Check first"]

Real Example

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# Load your image
cat_photo = mpimg.imread("cat.jpg")

# Display it!
plt.imshow(cat_photo)
plt.title("Look at this cute cat!")
plt.axis('off')  # Hide numbers
plt.show()

What’s Inside an Image?

When you load an image, it becomes a grid of numbers:

img = mpimg.imread("photo.png")
print(img.shape)
# Output: (480, 640, 3)
# Means: 480 rows, 640 columns, 3 colors (RGB)

5. Image Display Options – Making It Pretty

The Story

You loaded an image, but it looks weird! Colors are off, size is wrong, there are numbers everywhere. Let’s fix that!

The Key Display Options

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread("sunset.png")

# Basic display
plt.imshow(img)

# Clean display (no axis numbers)
plt.axis('off')

plt.show()

Colormaps – Changing Colors

For grayscale or scientific images:

# Gray colormap
plt.imshow(img, cmap='gray')

# Hot colormap (like heat map)
plt.imshow(img, cmap='hot')

# Cool colormap
plt.imshow(img, cmap='cool')

Common Colormaps

Colormap Best For
'gray' Black & white photos
'hot' Heat maps
'viridis' Scientific data
'plasma' Modern looks

Interpolation – Smoothing Pixels

# Pixelated (see each dot)
plt.imshow(img, interpolation='nearest')

# Smooth (blended)
plt.imshow(img, interpolation='bilinear')

# Very smooth
plt.imshow(img, interpolation='bicubic')

Setting Image Extent

Control WHERE the image appears:

# Place image at specific coordinates
plt.imshow(img, extent=[0, 10, 0, 5])
# Image now spans x: 0-10, y: 0-5

Complete Example

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# Load image
img = mpimg.imread("chart_bg.png")

# Display with all options
plt.figure(figsize=(8, 6))
plt.imshow(img,
           cmap='gray',
           interpolation='bicubic',
           aspect='auto')
plt.axis('off')
plt.title("My Beautiful Image")
plt.tight_layout()
plt.savefig("final.png", dpi=300)
plt.show()

🎯 Quick Summary

graph TD A["Figure Organization"] --> B["Saving"] A --> C["Loading"] B --> D["savefig - Save to file"] B --> E["Formats - PNG, JPG, PDF, SVG"] B --> F["DPI - Image quality"] C --> G["imread - Load images"] C --> H["imshow - Display options"]

The Golden Rules

  1. Save BEFORE show – or your file is blank!
  2. PNG for screens – JPG for photos, PDF for print
  3. DPI 300 for printing – 150 for screens
  4. imread() to loadimshow() to display
  5. axis('off') for clean looks – removes numbers

🚀 You Did It!

Now you can:

  • ✅ Save your charts to any format
  • ✅ Make them crystal sharp with DPI
  • ✅ Load external images
  • ✅ Display them beautifully

Your charts will never be trapped on screen again. Save them, share them, print them—the world is your gallery! 🎨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.