158

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

import numpy as np
import matplotlib.pyplot as plt

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

a = np.sin(t)
b = np.cos(t)
c = a + b
cottontail
  • 10,268
  • 18
  • 50
  • 51
user3277335
  • 1,947
  • 2
  • 15
  • 16

5 Answers5

249

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

Srivatsan
  • 9,225
  • 13
  • 58
  • 83
71

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

Jash Shah
  • 2,064
  • 4
  • 23
  • 41
8

Just use the function plot as follows

figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
nbro
  • 15,395
  • 32
  • 113
  • 196
leeladam
  • 1,748
  • 10
  • 15
3

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()
Linh
  • 33
  • 5
  • What is an ROC curve? – Cheng Sep 16 '22 at 10:16
  • Receiver operating characteristic. It's used in the context of stats to show how a hypothesis test behaves for a given threshold. For instance you may have a binary classifier that takes some input x, applies some function f(x) to it and predicts H1 if f(x) > t. t is your threshold that you use to decide whether to predict H0 or H1. Varying that threshold will yield different true positive rate-false positive rate pairs. The ROC curve captures that. The name comes from early applications of hypothesis testing in the military to decide whether a radar was raising a false alarm @Cheng – Joud C Feb 04 '23 at 00:15
0

A pretty concise method is to concatenate the function values horizontally to make an array of shape (len(t), 3) and call plot().

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

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

plt.plot(t, np.c_[a, b, c]);

If the data doesn't come from a numpy array and you don't want the numpy dependency, zip() is your friend.

plt.plot(t, list(zip(a, b, c)));

Since there are 3 different graphs on a single plot, perhaps it makes sense to insert a legend in to distinguish which is which. That can be done easily by passing the label.

plt.plot(t, np.c_[a, b, c], label=['sin', 'cos', 'sin+cos']);
plt.legend();

img1

cottontail
  • 10,268
  • 18
  • 50
  • 51