pyplot-tutorial








common use cases for matplotlib (pyplot functional API)

This is a collection of code snippets to cover most common use cases of using matplotlib library

In [1]:
import numpy as np

1. Initialize

In [2]:
import matplotlib.pyplot as plt

2. Plot some data

In [3]:
data = np.random.rand(20)*10
plt.plot(data)
plt.show()

3. show an image

In [4]:
img = np.random.rand(30, 30, 3)
plt.imshow(img)    # changed
plt.show()

4. plot size

In [5]:
plt.figure(figsize=(10,10))    # changed
data = np.random.rand(20)*10
plt.plot(data)
plt.show()

5. multiple data plotting

In [6]:
data1 = np.random.rand(20)*10
data2 = np.random.rand(20)*10    
plt.plot(data1)
plt.plot(data2)    # changed
plt.show()

6. set plot color

In [8]:
data1 = np.random.rand(20)*10
data2 = np.random.rand(20)*10
plt.plot(data1, color='g')    # changed
plt.plot(data2, color='r')    # changed
plt.show()

7. plot legend

In [9]:
data1 = np.random.rand(20)*10
data2 = np.random.rand(20)*10
plt.plot(data1, color='g', label='data1')    # changed
plt.plot(data2, color='r', label='data2')    # changed
plt.legend()    # changed
plt.show()

8. axis turn on/off

In [15]:
data1 = np.random.rand(20)*10
data2 = np.random.rand(20)*10
plt.axes = 0
plt.plot(data1, color='g', label='data1')
plt.plot(data2, color='r', label='data2')
plt.xticks([])    # changed
plt.yticks([])    # changed
plt.legend()
plt.show()

9. major ticks

In [21]:
data1 = np.random.rand(20)*10
data2 = np.random.rand(20)*10
plt.axes = 0
plt.plot(data1, color='g', label='data1')
plt.plot(data2, color='r', label='data2')
plt.xticks(np.linspace(0, 20, 4, endpoint=False))    # changed
# plt.yticks([])
plt.legend()
plt.show()

10. minor ticks

In [11]:
data1 = np.random.rand(20)*10
data2 = np.random.rand(20)*10
plt.plot(data1, color='g', label='data1')
plt.plot(data2, color='r', label='data2')
plt.xticks(np.linspace(0, 20, 4, endpoint=False))
plt.axes().xaxis.set_minor_locator(plt.MultipleLocator(1))    # changed
# plt.yticks([])
plt.legend()
plt.show()

11. grid

In [12]:
data1 = np.random.rand(20)*10
plt.plot(data1, color='g', label='data1')
plt.xticks(np.linspace(0, 20, 4, endpoint=False))
plt.axes().xaxis.set_minor_locator(plt.MultipleLocator(1))
# plt.yticks([])
plt.legend()
plt.grid(True, which='both')    # changed
plt.show()

12. Axis limits

In [16]:
data1 = np.random.rand(20)*10
plt.axes().xaxis.set_minor_locator(plt.MultipleLocator(1))
plt.plot(data1, color='g', label='data1')
plt.xticks(np.linspace(0, 20, 4, endpoint=False))
plt.xlim(0, 50)    # changed
plt.ylim(0, 20)    # changed
# plt.yticks([])
plt.legend()
plt.grid(True, which='both')
plt.show()
In [ ]: