5

In order to draw two graphs in one plot with python's matplotlib.pyplot, one would typically do this:

import matplotlib.pyplot as plt

xdata = [0, 1, 2, 3, 4]
ydata1 = [0, 1, 2, 3, 4]
ydata2 = [0, 0.5, 2, 4.5, 8]

plt.plot(xdata, ydata1, 'r-', xdata, ydata2, 'b--')
plt.show()

However, I would like to draw the second dataset only under certain circumstances, like this:

plt.plot(xdata, ydata1, 'r-')

if DrawSecondDataset:
    plt.plot(data, ydata2, 'b--')

Unfortunately, calling plot for the second time means that the first dataset is erased.

How can you add a graph to an already existing plot?

EDIT:

As the answers pointed out correctly, the dataset is only erased if plt.show() has been called between the two plt.plot() commands. Thus, the example above actually shows both datasets.

For completeness: Is there an option to add a graph to an existing plot on which plt.show() has already been called? Such as

plt.plot(xdata, ydata1, 'r-')
plt.show()

...

plt.plot(data, ydata2, 'b--')
plt.show()
2
  • "Unfortunately, calling plot for the second time means that the first dataset is erased" No it doesn't. Commented Dec 22, 2016 at 17:40
  • Yes, you are right. It only is when you call show in between. I have updated my question. Commented Dec 23, 2016 at 6:34

3 Answers 3

2

Just call show() at the very end.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that works. But only if you haven't called show before. Do you also know how to add a graph after show has been called.
To answer my own question: After you have called show, the next plot command will clear the plot. Then, you can again call plot twice to add two plots. Thank you very much.
0
if DrawSecondDataset:
    plt.plot(data, ydata2, 'b--')
    plt.show() #to display it

Comments

0

The first data won't be erased in this way

plt.plot(xdata, ydata1, 'r-')

if DrawSecondDataset:
    plt.plot(data, ydata2, 'b--')

plt.show()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.