# import
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# generating some data points
X = np.linspace(-np.pi, np.pi, 20, endpoint=True)
C, S = np.cos(X), np.sin(X)
# Simply plotting these in same plot
plt.plot(X, C,
X, S)
[<matplotlib.lines.Line2D at 0x78312e8>, <matplotlib.lines.Line2D at 0x7831cf8>]
** Adding a Legends **
plt.plot(X, C, label='Cos')
plt.plot(X, S, label='Sin')
plt.legend(loc='upper right')
<matplotlib.legend.Legend at 0x7d11c88>
plt.plot(X, C, label='Cos')
plt.plot(X, S, label='Sin')
plt.legend(loc='best') # python itself choose the best location for legends
<matplotlib.legend.Legend at 0x7d85630>
# 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
<matplotlib.legend.Legend at 0x7e64f28>
# 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
<matplotlib.legend.Legend at 0x7ed4dd8>
# 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
Line2D(_line0) Line2D(_line1)
<matplotlib.legend.Legend at 0x902eeb8>
** Adding Grid & Margins **
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 **
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())
Current Limits (-4.3982297150257104, 4.3982297150257104) (-1.399316898601334, 1.3959013916080039)
** Changing Limits **
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])
Current Limits (-4.3982297150257104, 4.3982297150257104) (-1.399316898601334, 1.3959013916080039)
(-1.5, 1.5)
** Changing Plot Size **
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%