Reputation: 1310
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()
Upvotes: 5
Views: 21792
Reputation: 1215
The first data won't be erased in this way
plt.plot(xdata, ydata1, 'r-')
if DrawSecondDataset:
plt.plot(data, ydata2, 'b--')
plt.show()
Upvotes: 0
Reputation: 5704
if DrawSecondDataset:
plt.plot(data, ydata2, 'b--')
plt.show() #to display it
Upvotes: 0