Save matplotlib figure as a SVG using Python
In this tutorial, we will learn how to save a matplotlib figure as an SVG file using Python.
SVG stands for scalable vector graphics. It is an XML file, used for describing tw0 dimensional graphics.
Here we will save the output figure of the program as an SVG file, we use NumPy and matplotlib modules of Python to do this.
How to save matplotlib figure in SVG format
Firstly let’s Import the modules required.import matplotlib.pyplot as plt import numpy as np
import matplotlib.pyplot as plt import numpy as np
Now let’s create two arrays using Numpy for storing the values of x-coordinates and y-coordinates. And then plot the coordinates using the matplotlib library. Here I am using scatter plotting for plotting the coordinates. then label the coordinates X and Y respectively. And finally, save the output of the code using the method called savefig.
#creating Arrays x_coordinates = np.array([1,3,4,5,8,6,4,3,9,6]) y_coordinates = np.array([0,5,7,1,3,2,8,1,7,9]) #plotting the points plt.scatter(x_coordinates, y_coordinates) #labelling the coordinate axes plt.ylabel("Y-axis") plt.xlabel("X-axis") #saving the figure as SVG #give the address where the file should be saved as a parameter plt.savefig('D:\codespeedy/img.svg',dpi=350) #showing the output plt.show()
For the savefig method, we will pass the address to which you want your file to be saved, in the above example I saved it in my D drive. And I saved it as a .svg file since we wanted it in that format. we can use any other format like .pdf, .jpg,.jpeg, .png, and EPS, the dpi parameter is used for improving the quality of the picture. And dpi stands for dots per inch. Finally, we show the output using show().
Output:
Here you can see that the image is saved on my required folder:
After executing the above code and mentioning the required folder in the savefig method, then you can get the file in your destination folder.
Leave a Reply