Non-interactive backends

We have been using several non-interactive backends so far, which include Agg, Cairo, GDK, PDF, PGF, PS, and SVG. Most of these backends work without extra dependencies, but Cairo and GDK require the Cairo graphics library or GIMP Drawing Kit, respectively, to work.

Non-interactive backends can be further classified into two groups—vector or raster. Vector graphics describe images in terms of points, paths, and shapes that are calculated using mathematical formulas. A vector graphic will always appear smooth irrespective of the scale, and its size is usually much smaller than the raster counterpart. PDF, PGF, PS, and SVG backends belong to the vector group.

Raster graphics describe images in terms of a finite number of tiny color blocks (pixels). So if we zoom in enough, we start to see an unsmooth representation of the image, in other words, pixelation. By increasing the resolution or dots per inch (DPI) of the image, we are less likely to observe pixelation. Agg, Cairo, and GDK belong to this group of backends. The following table summarizes the key functionalities and differences among the non-interactive backends:

Backend Vector or raster? Output formats
Agg Raster .png
Cairo Vector/Raster .pdf, .png, .ps, .svg
PDF Vector .pdf
PGF Vector .pdf, .pgf
PS Vector .ps
SVG Vector .svg
GDK* Raster .png, .jpg, .tiff

*Deprecated in Matplotlib 2.0.

Normally, we don't need to manually select a backend, as the default choice would work great for most tasks. On the other hand, we can specify a backend through the matplotlib.use() method before importing matplotlib.pyplot for the first time:

import matplotlib
matplotlib.use('SVG') # Change to SVG backend
import matplotlib.pyplot as plt
import textwrap # Standard library for text wrapping

# Create a figure
fig, ax = plt.subplots(figsize=(6,7))

# Create a list of x ticks positions
ind = range(df.shape[0])

# Plot a bar chart of median usual weekly earnings by educational attainments
rects = ax.barh(ind, df["Median usual weekly earnings ($)"], height=0.5)

# Set the x-axis label
ax.set_xlabel('Median weekly earnings (USD)')

# Label the x ticks
# The tick labels are a bit too long, let's wrap them in 15-char lines
ylabels=[textwrap.fill(label,15) for label in df["Educational attainment"]]
ax.set_yticks(ind)
ax.set_yticklabels(ylabels)

# Give extra margin at the bottom to display the tick labels
fig.subplots_adjust(left=0.3)

# Save the figure in SVG format
plt.savefig("test.svg")
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.149.144