How to tell Matplotlib about creating a second (new) plot, and then about the plot on the old?

I want to build data, then create a new shape and build data2, and finally return to the original plot and data3 plot, sort of like:

import numpy as np import matplotlib as plt x = arange(5) y = np.exp(5) plt.figure() plt.plot(x, y) z = np.sin(x) plt.figure() plt.plot(x, z) w = np.cos(x) plt.figure("""first figure""") # Here the part I need plt.plot(x, w) 

FYI How do I tell matplotlib that I ended up with a plot? does something like that, but not really! This does not allow me to access this original plot.

+68
python matplotlib plot figure
Aug 02 '11 at 18:45
source share
4 answers

If you regularly do this, it might be worth exploring the object-oriented matplotlib interface. In your case:

 import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y = np.exp(x) fig1 = plt.figure() ax1 = fig1.add_subplot(111) ax1.plot(x, y) z = np.sin(x) fig2 = plt.figure() ax2 = fig2.add_subplot(111) ax2.plot(x, z) w = np.cos(x) ax1.plot(x, w) # can continue plotting on the first axis 

This is a bit more verbose, but it is much clearer and easier to track, especially with multiple digits, each with multiple subheadings.

+89
Aug 04 '11 at 1:40
source share

When you call figure , just specify the graph.

 x = arange(5) y = np.exp(5) plt.figure(0) plt.plot(x, y) z = np.sin(x) plt.figure(1) plt.plot(x, z) w = np.cos(x) plt.figure(0) # Here the part I need plt.plot(x, w) 

Edit: note that you can number the graphs, but you want (here, starting at 0 ), but if you don’t specify a number with a number at all when creating a new one, automatic numbering starts from 1 ("Matlab Style" according to the docs) .

+50
Aug 02 '11 at 18:50
source share

However, the numbering starts with 1 , therefore:

 x = arange(5) y = np.exp(5) plt.figure(1) plt.plot(x, y) z = np.sin(x) plt.figure(2) plt.plot(x, z) w = np.cos(x) plt.figure(1) # Here the part I need, but numbering starts at 1! plt.plot(x, w) 

Also, if you have several axes in the shape, such as subtitles, use the axes(h) command, where h is the handle to the desired axis object to focus on these axes.

(while you have no comments yet, sorry for the new answer!)

+7
Aug 02 2018-11-11T00:
source share

One of the ways that I found after some struggle creates a function that receives the data_plot matrix, file name and order as a parameter for creating boxes from data in an ordered picture (different orders = different numbers) and saves it under the given file name.

 def plotFigure(data_plot,file_name,order): fig = plt.figure(order, figsize=(9, 6)) ax = fig.add_subplot(111) bp = ax.boxplot(data_plot) fig.savefig(file_name, bbox_inches='tight') plt.close() 
0
Nov 22 '17 at 21:59
source share



All Articles