In [1]:
# import
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [2]:
# generating some data points
X = np.linspace(-np.pi, np.pi, 20, endpoint=True)
C, S = np.cos(X), np.sin(X)
In [3]:
# Simply plotting these in same plot
plt.plot(X, C,
X, S)
Out[3]:
Adding a Legends
In [6]:
plt.plot(X, C, label='Cos')
plt.plot(X, S, label='Sin')
plt.legend(loc='upper right')
Out[6]:
In [7]:
plt.plot(X, C, label='Cos')
plt.plot(X, S, label='Sin')
plt.legend(loc='best') # python itself choose the best location for legends
Out[7]:
In [9]:
# one more way to add legends
l1, = plt.plot(X, C)
l2, = plt.plot(X, S)
plt.legend([l1, l2],loc='best') # this will print the legends generated by matplotlib
Out[9]:
In [10]:
# let's modify the matplotlib generated labels
l1, = plt.plot(X, C)
l2, = plt.plot(X, S)
plt.legend([l1, l2],["Cos Wave", "Sin Wave"], loc='best') # python itself choose the best location for legends
Out[10]:
In [21]:
# What if we are plotting multiple charts in single plot
l1,l2, = plt.plot(X, C, X, S)
print(l1, l2)
plt.legend([l1, l2],["Cos Wave", "Sin Wave"], loc='best') # python itself choose the best location for legends
Out[21]:
Adding Grid & Margins
In [28]:
l1,l2, = plt.plot(X, C, X, S)
plt.legend([l1, l2],["Cos Wave", "Sin Wave"], loc='best')
# adding Grid & Margins
plt.grid(True)
plt.margins(0.2) # 20%
Modifying axis limits
In [30]:
l1,l2, = plt.plot(X, C, X, S)
plt.legend([l1, l2],["Cos Wave", "Sin Wave"], loc='best')
# adding Grid & Margins
plt.grid(True)
plt.margins(0.2) # 20%
# printing current limits
print("Current Limits")
print(plt.xlim())
print(plt.ylim())
Changing Limits
In [40]:
l1,l2, = plt.plot(X, C, X, S)
plt.legend([l1, l2],["Cos Wave", "Sin Wave"], loc='best')
# adding Grid & Margins
plt.grid(True)
plt.margins(0.2) # 20%
# printing current limits
print("Current Limits")
print(plt.xlim())
print(plt.ylim())
# modifyint limits
plt.xlim([-6, 6])
plt.ylim([-1.5, 1.5])
Out[40]:
Changing Plot Size
In [41]:
plt.figure(figsize=(8,6))
l1,l2, = plt.plot(X, C, X, S)
plt.legend([l1, l2],["Cos Wave", "Sin Wave"], loc='best')
# adding Grid & Margins
plt.grid(True)
plt.margins(0.2) # 20%
In [ ]: