How can I get the output of a Matplotlib plot as an SVG?


Just using the savefig method of the pyplot package and mentioning the file format, we can save the output as a SVG format.

Steps

  • Create fig and ax variables using subplots method, where default nrows and ncols are 1.

  • Create xpoints and ypoints using np.array(0, 5).

  • Plot lines using xpoints and ypoints.

  • Set the X-axis label using plt.xlabel() method.

  • Set the Y-axis label using plt.ylabel() method.

  • To save the file in SVG format, use savefig() method where image name is myImagePDF.svg, format="svg".

  • To show the image, use plt.show() method.

Example

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
xpoints = np.array([0, 5])
ypoints = np.array([0, 5])
plt.plot(xpoints, ypoints)

plt.ylabel("Y-axis ")
plt.xlabel("X-axis ")

image_format = 'svg' # e.g .png, .svg, etc.
image_name = 'myimage.svg'

fig.savefig(image_name, format=image_format, dpi=1200)

Output

Updated on: 17-Mar-2021

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements