Matplotlib plt.show () only selected objects

I have several instances of plt.plot , and I only wanted plt.show() specific objects. For illustration, here is the code:

 import matplotlib.pyplot as plt ax1 = plt.plot(range(5),range(5)) ax2 = plt.plot([x+1 for x in range(5)],[x+1 for x in range(5)]) ax3 = plt.plot([x+2 for x in range(5)],[x+2 for x in range(5)]) #plt.show([ax1,ax2]) plt.show() 

So, I would like something like a commented statement to display only the ax1 and ax2 currents in the example.

+4
source share
2 answers

You can remove some of the plotted lines from the rowset of the current axes:

 axes = plt.gca() # Get current axes axes.lines.remove(ax2[0]) # Removes the (first and only) line created in ax2 plt.draw() # Updates the graph (in interactive mode) 

If you want to return it, you can also do

 axes.lines.append(ax2[0]) # Puts the line back (the drawing order is changed, here) 

You can also save the current chart lines if you need to return them later:

 all_lines = list(axes.lines) # Copy # ... axes.lines[:] = all_lines # All lines put back 

The key point is that each plot() command adds a line to the current axes and draws it (interactively). That way, you can either delete the lines already built (as in this answer).

As Yann pointed out, you can also make some invisible lines. However, the method from this answer is probably faster since fewer lines are drawn (if that matters).

+3
source

Not really. First, calling plt.plot does not return an axis; it returns a list of Line2D objects, one for each line. You can use the OO interface for Matplotlib to create separate axes for each plot, then selectively add them as subtitles, etc. There are many ways to selectively reveal a plot.

But for your example, you can use the value of the alpha line Line2D, i.e. opaque to make any one invisible line. Here is a modified version of your example:

 import matplotlib.pyplot as plt line1 = plt.plot(range(5),range(5)) line2 = plt.plot([x+1 for x in range(5)],[x+1 for x in range(5)]) line3 = plt.plot([x+2 for x in range(5)],[x+2 for x in range(5)]) print line3, " see I'm a list of lines" print line3[0].get_alpha() line3[0].set_alpha(0) # make complete opaque #plt.show([ax1,ax2]) plt.gcf().savefig('line3opaque.png') line3[0].set_alpha(1) # make visible line1[0].set_alpha(0) # make opaque plt.gcf().savefig('line1opaque.png') plt.show() 

The first figure I saved is 'line3opaque.png'; this is what i get:

enter image description here Line 3 is missing, and lines 1 and 2. For 'line1opaque.png' I get:

enter image description here

Now we are missing line 1.

+3
source

Source: https://habr.com/ru/post/1382306/


All Articles