[Python] Loss of quality when plotting many lines with alpha<1 with matplotlib

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a publication-quality graph that nicely shows the density of where randomly generated lines fall on a plot. However, when I try to save these plots in .svg format, there is always a loss in quality because I think the lines are being rasterized. Calling the set_rasterized function doesn't appear to help.

    Is there a way to force matplotlib to save these lines in vector format, or at least save them at higher quality so the images don't look terrible when zoomed in? Saving as a .png with high DPI does not help either.

    import matplotlib.pyplot as plt
    import numpy as np

    num_lines = 1000
    np.random.seed(42)
    xs = np.linspace(0, 10, 100).reshape(1,-1)
    ys = xs*np.random.normal(1,1,(num_lines,1)) + np.random.normal(0, 1, (num_lines,100))
    for y in ys:
    l = plt.plot(xs.flatten(), y, 'k', alpha=0.01)
    l[0].set_rasterized(False)

    plt.savefig('ex.svg')

    plt.show()


    Example of zoomed in plot

    Continue reading...

Compartilhe esta Página