Search code examples
pythonpython-3.xmatplotlibsvgresolution

Create a detailed svg graph with matplotlib


I use the Python library matplotlib to draw a graph with a lot of data. Upon executing plt.show() I can zoom in and see the details of the graph. However, I would like to save the graph into a svg file with plt.savefig and see these details which by default are not visible from the default non-zoomed-in view. How can I do that?

Please, note that increasing DPI or inch by inch dimensions is meaningless when working with vector graphics formats such as the svg file.

As an example, consider the following program.

import matplotlib.pyplot as plt
import numpy as np
import math

x = np.arange(0,100,0.00001)
y = x*np.sin(2*math.pi*(x**1.2))
plt.plot(y)
plt.savefig('test.svg')

We will get the following plot which even when we zoom, we cannot see the details of the sine wave periods.enter image description here

But we can see the details of the sine wave when displaying the image with plt.show instead and then zooming in.enter image description here


Solution

  • Add the size of the figure:

    import matplotlib.pyplot as plt
    import numpy as np
    import math
    
    x = np.arange(0,100,0.00001)
    y = x*np.sin(2*math.pi*(x**1.2))
    fig = plt.figure(figsize=(19.20,10.80))
    
    plt.plot(y)
    plt.savefig('test.svg')
    

    and you get the kind of resolution you wish.


    As correctly observed by JohanC, another good solution is to reduce the width of the line:

    import matplotlib.pyplot as plt
    import numpy as np
    import math
    
    x = np.arange(0,100,0.00001)
    y = x*np.sin(2*math.pi*(x**1.2))
    #fig = plt.figure(figsize=(19.20,10.80))
    
    plt.plot(y, linewidth=0.1)
    plt.savefig('test.svg')