Python

How do I create a second new plot then later plot on the old one

27 September 2026 · 10 min read

How do I create a second new plot then later plot on the old one

Data visualization is a cornerstone of modern data analysis. One common task that arises is the need to create a second, entirely new plot, while also retaining the ability to plot data on the original one later. Understanding how to manage multiple plots efficiently in your chosen programming language or visualization tool is crucial for comparing datasets, exploring different perspectives, or creating complex dashboards. This article will guide you through the process of learning how to create a second (new) plot, then later plot on the old one, ensuring you can effectively manage and manipulate your visualizations for maximum impact. We’ll cover the essential techniques and best practices to help you master this fundamental skill.

Understanding Plotting Contexts and Objects

Before diving into the code, it’s important to grasp the underlying concepts. When you generate a plot, you’re typically working within a specific plotting “context” or with plot “objects.” These contexts or objects hold all the information about your plot: the data, axes, labels, and styling. Different plotting libraries (like Matplotlib in Python or ggplot2 in R) handle these contexts differently. Understanding how your chosen library manages plots is key to creating multiple plots and switching between them. Failing to understand these fundamentals can lead to unexpected behavior and difficulty in managing your visualizations. It is important to keep track of which plot is active, and how to activate a different plot when needed.

Think of it like having multiple canvases in an art studio. Each canvas represents a separate plot, and you need to be able to select which canvas you’re currently painting on. Similarly, in programming, you need to tell your plotting library which plot object you want to modify or add data to. This often involves using specific commands to create a new figure or activate an existing one. The ability to switch between these canvases freely and efficiently is what allows you to compare and contrast different data representations.

For example, in Matplotlib, you typically use the plt.figure() function to create a new figure, which serves as a container for your plot. Each figure can contain multiple subplots, allowing you to arrange several plots within a single window. The concept of a “current” figure and axes is crucial. Most plotting commands implicitly operate on the current figure and axes. To switch to a different figure, you often need to explicitly specify it. This understanding is the foundation for effectively managing multiple plots.

Creating a New Plot

The specific steps for creating a new plot will vary depending on the plotting library you’re using. However, the general principle remains the same: you need to create a new plotting context or object that is distinct from your existing plot. Let’s consider the example of Matplotlib in Python, a popular choice for data visualization. To create a new plot, you would typically use the plt.figure() function. This function creates a new figure object, which you can then populate with data and customize as needed.

Here’s a basic example:

import matplotlib.pyplot as plt Create the first plot plt.plot([1, 2, 3, 4], [5, 6, 7, 8]) plt.title('First Plot') Create a second, new plot plt.figure() This creates a new figure object plt.plot([1, 2, 3, 4], [9, 10, 11, 12]) plt.title('Second Plot') plt.show() 

In this example, plt.figure() creates a completely separate figure, ensuring that subsequent plotting commands affect only the new plot. Without this, the second plt.plot() command would overwrite the first plot. This simple example demonstrates the core principle: explicitly creating a new figure to start a new visualization. This example shows you how to create two separate plots. To enhance your visualization, consider adding axis labels using plt.xlabel() and plt.ylabel(). (Source: Matplotlib Documentation)

Plotting on the Original Plot Later

Now, let’s say you want to go back and add data to your original plot. This requires you to reactivate the original plotting context or object. Again, the specific commands will depend on your plotting library. In Matplotlib, you can achieve this by keeping track of the figure objects you create. You can assign each figure to a variable and then use that variable to refer to the figure later.

Here’s how you can modify the previous example to plot on the original plot after creating a new one:

import matplotlib.pyplot as plt Create the first plot and assign it to a variable fig1 = plt.figure() plt.plot([1, 2, 3, 4], [5, 6, 7, 8]) plt.title('First Plot') Create a second, new plot plt.figure() plt.plot([1, 2, 3, 4], [9, 10, 11, 12]) plt.title('Second Plot') Switch back to the first plot and add more data plt.figure(fig1.number) Activate the first figure plt.plot([1, 2, 3, 4], [2, 4, 6, 8], 'r--') Plot additional data on the first plot plt.legend(['Original Data', 'New Data']) plt.show() 

In this example, fig1 stores the first figure object. Later, plt.figure(fig1.number) reactivates that figure, allowing you to add more data to it. The ‘r–’ argument specifies a red dashed line style for the new data, and plt.legend() adds a legend to distinguish between the original and new data. This ability to switch between plots is key to managing complex visualizations and comparing different datasets. Always remember to keep track of your figure objects to easily revert and make more edits.

This technique is particularly useful when you want to compare different datasets on the same plot or add annotations or labels to an existing visualization. By mastering the art of switching between plotting contexts, you gain greater control over your data visualization workflow.

Best Practices and Advanced Techniques

Beyond the basics, there are several best practices and advanced techniques that can further enhance your ability to manage multiple plots. One important consideration is the use of subplots. Subplots allow you to arrange multiple plots within a single figure, providing a convenient way to compare related visualizations side-by-side. Matplotlib provides the plt.subplot() function for creating subplots, allowing you to specify the number of rows and columns in the subplot grid, as well as the index of the current subplot.

For example:

import matplotlib.pyplot as plt Create a figure with two subplots plt.figure(figsize=(10, 5)) Adjust figure size for better visualization First subplot plt.subplot(1, 2, 1) (rows, columns, panel number) plt.plot([1, 2, 3, 4], [5, 6, 7, 8]) plt.title('First Subplot') Second subplot plt.subplot(1, 2, 2) plt.plot([1, 2, 3, 4], [9, 10, 11, 12]) plt.title('Second Subplot') plt.tight_layout() Adjust subplot parameters for a tight layout. plt.show() 

This code creates a figure with two subplots arranged side-by-side. The plt.subplot(1, 2, 1) command creates the first subplot (one row, two columns, first panel), and plt.subplot(1, 2, 2) creates the second subplot. This approach is ideal for comparing different aspects of your data within a single visualization. Another useful technique is to use object-oriented plotting. Instead of relying on the implicit state of the current figure and axes, you can create explicit figure and axes objects and manipulate them directly. This can lead to more readable and maintainable code, especially for complex visualizations. (Source: Real Python Matplotlib Tutorial)

Here are some key points to remember:

  • Always explicitly create a new figure when you want to start a new plot.
  • Keep track of your figure objects so you can reactivate them later.
  • Consider using subplots for comparing related visualizations.
Infographic here: A visual representation of the steps involved in creating and switching between plots.
### Advanced Techniques for Complex Visualizations

For more advanced scenarios, consider using object-oriented plotting in Matplotlib. This approach gives you finer control over each element of your plot. You create Figure and Axes objects explicitly, allowing you to manipulate them directly. This can be particularly useful when building complex visualizations with many subplots and custom elements.

import matplotlib.pyplot as plt Create a figure and an axes. fig, ax = plt.subplots() Plot some data on the axes. ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) Add some labels. ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_title("Simple Plot") plt.show() 

This approach offers a cleaner and more structured way to build visualizations, especially as they grow in complexity. Also, consider using libraries like Seaborn, which is built on top of Matplotlib and provides a higher-level interface for creating statistical graphics. Seaborn can simplify many common plotting tasks and help you create visually appealing and informative visualizations with less code. (Seaborn Documentation)

Here’s a list of steps that are generally required:

  1. Import the necessary plotting library (e.g., Matplotlib).
  2. Create your initial plot using the appropriate functions (e.g., plt.plot()).
  3. Create a new figure to start a second plot (e.g., plt.figure()).
  4. Plot your data on the new figure.
  5. If you want to plot on the original plot again, reactivate it using the appropriate method (e.g., plt.figure(fig1.number)).
  6. Add any additional data or customizations to the original plot.
  7. Display your plots (e.g., plt.show()).

Understanding and implementing these steps will streamline your workflow and help you create powerful visualizations.

FAQ

**Q: How do I prevent my second plot from overwriting the first one in Matplotlib?**
A: Use `plt.figure()` before creating the second plot. This creates a new figure object, ensuring that subsequent plotting commands affect only the new plot.
**Q: Can I create multiple plots in the same window?**
A: Yes, you can use subplots. The `plt.subplot()` function allows you to divide a figure into multiple panels and plot different data in each panel.
**Q: How can I add a legend to my plot in Matplotlib?**
A: Use the `plt.legend()` function. Make sure to label your plot elements (e.g., using the `label` argument in `plt.plot()`) so that the legend can correctly identify them.
Mastering the ability to **create a second (new) plot, then later plot on the old one** is a fundamental skill for any data analyst or scientist. By understanding plotting contexts, using appropriate functions, and following best practices, you can effectively manage multiple visualizations and gain deeper insights from your data. Remember to practice with different plotting libraries and explore advanced techniques like subplots and object-oriented plotting to further enhance your skills.

Effective data visualization is crucial for understanding and communicating complex information. By mastering these techniques, you can unlock the full potential of your data and create compelling visuals that tell a story. Now, go forth and experiment with different plotting libraries, explore advanced techniques, and unleash your creativity to create stunning and informative visualizations. Consider exploring related topics such as customizing plot styles, adding annotations, and creating interactive visualizations. Dive deeper into data visualization and unlock new insights into the world around you. Check out our detailed guide on data analysis techniques for more information.

Question & Answer :
I want to plot data, then create a new figure and plot data2, and finally come back to the original plot and plot data3, kinda like this:

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's the part I need plt.plot(x, w) 

FYI How do I tell matplotlib that I am done with a plot? does something similar, but not quite! It doesn’t let me get access to that original plot.

If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:

import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y = np.exp(x) fig1, ax1 = plt.subplots() ax1.plot(x, y) ax1.set_title("Axis 1 title") ax1.set_xlabel("X-label for axis 1") z = np.sin(x) fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure ax2.plot(x, z) ax3.plot(x, -z) w = np.cos(x) ax1.plot(x, w) # can continue plotting on the first axis 

It is a little more verbose but it’s much clearer and easier to keep track of, especially with several figures each with multiple subplots.