Matplotlib tutorial 03


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]:
[<matplotlib.lines.Line2D at 0x78312e8>,
 <matplotlib.lines.Line2D at 0x7831cf8>]

Adding a Legends


In [6]:
plt.plot(X, C, label='Cos')
plt.plot(X, S, label='Sin')

plt.legend(loc='upper right')


Out[6]:
<matplotlib.legend.Legend at 0x7d11c88>

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]:
<matplotlib.legend.Legend at 0x7d85630>

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]:
<matplotlib.legend.Legend at 0x7e64f28>

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]:
<matplotlib.legend.Legend at 0x7ed4dd8>

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


Line2D(_line0) Line2D(_line1)
Out[21]:
<matplotlib.legend.Legend at 0x902eeb8>

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())


Current Limits
(-4.3982297150257104, 4.3982297150257104)
(-1.399316898601334, 1.3959013916080039)

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])


Current Limits
(-4.3982297150257104, 4.3982297150257104)
(-1.399316898601334, 1.3959013916080039)
Out[40]:
(-1.5, 1.5)

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 [ ]: