How to plot multiple functions on the same figure, in Matplotlib?

PythonFunctionMatplotlibGraph

Python Problem Overview


How can I plot the following 3 functions (i.e. sin, cos and the addition), on the domain t, in the same figure?

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0, 2*math.pi, 400)

a = sin(t)
b = cos(t)
c = a + b

Python Solutions


Solution 1 - Python

To plot multiple graphs on the same figure you will have to do:

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, 'r') # plotting t, a separately 
plt.plot(t, b, 'b') # plotting t, b separately 
plt.plot(t, c, 'g') # plotting t, c separately 
plt.show()

enter image description here

Solution 2 - Python

Perhaps a more pythonic way of doing so.

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

Solution 3 - Python

Just use the function plot as follows

figure()
...
plot(t, a)
plot(t, b)
plot(t, c)

Solution 4 - Python

If you want to work with figure, I give an example where you want to plot multiple ROC curves in the same figure:

from matplotlib import pyplot as plt
plt.figure()
for item in range(0, 10, 1): 
    plt.plot(fpr[item], tpr[item])
plt.show()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3277335View Question on Stackoverflow
Solution 1 - PythonSrivatsanView Answer on Stackoverflow
Solution 2 - PythonJash ShahView Answer on Stackoverflow
Solution 3 - PythonleeladamView Answer on Stackoverflow
Solution 4 - PythonLinhView Answer on Stackoverflow