简体   繁体   中英

Python matplotlib keeps the previous line after plotting new one

The method that I have been using to plot the lines are as following:

def scatter_plot_with_correlation_line(x, y, graph_filepath):
    plt.scatter(x, y)
    axes = plt.gca()
    m, b = np.polyfit(x, y, 1)
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)
    plt.plot(X_plot, m*X_plot + b, '-')
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')

The first plot looks fine:

在此处输入图片说明

Now in the second plot the previous line is still visible: 在此处输入图片说明

Since I am using the scatter_plot_with_correlation_line() in a loop the results get worse with every iteration.

The following plot is after 10th iteration. 在此处输入图片说明

How can I remove the previous line plotted from the new ones ?

Do you want to remove the scatter plot and the line, and then replot them both? if so, you could simply clear the current axes at the beginning of your function using plt.gca().cla()

def scatter_plot_with_correlation_line(x, y, graph_filepath):
    plt.gca().cla()
    plt.scatter(x, y)
    axes = plt.gca()
    m, b = np.polyfit(x, y, 1)
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)
    plt.plot(X_plot, m*X_plot + b, '-')
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')

If you only want to remove the line, and retain the previously plotted scatter points, then you could grab a reference to the line2D object as you plot it, and then remove it later:

def scatter_plot_with_correlation_line(x, y, graph_filepath):
    plt.scatter(x, y)
    axes = plt.gca()
    m, b = np.polyfit(x, y, 1)
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)

    # Store reference to correlation line. note the comma after corr_line
    corr_line, = plt.plot(X_plot, m*X_plot + b, '-')
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')

    # remove the correlation line after saving the figure, ready for the next iteration
    corr_line.remove()

Try plt.clear() in the beginning or the end of your function.

If it does not work correct in your way: Try to split the scatter plot from the line plot and clear only the line plot. ;)

Use a new figure

def scatter_plot_with_correlation_line(...):
    ######################
    f, ax = plt.subplots()
    ######################
    ax.scatter(...)
    ax.plot(...)
    f.savefig(...)

another possibility consists in clearing the lines already drawn from your axis

    ...
    axes = plt.gca()
    axes.lines = []
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM