Matplotlib

source

Importing the Relevant Libraries

In [1]:
import numpy as np
import matplotlib.pyplot as plt

Line Chart

In [2]:
x = np.linspace(0, 30, 1000)

y = 0.5 * x

plt.plot(x, y)

plt.xlabel('Input')
plt.ylabel('Output')
plt.title('Line Chart')
plt.savefig('linechart.png')

plt.show()
In [3]:
x = np.linspace(0, 30, 1000)

y = 0.5 * x

plt.plot(x,y,linestyle='dashed',linewidth=3, markersize=12)

plt.xlabel('Input')
plt.ylabel('Output')
plt.title('Line Chart')
plt.savefig('linechart2.png')

plt.show()

Scatterplot

Sample 1

 - np.random.randn(100, 2) 

       -> 100 random observations
       -> 2D Array

 - random_variables[:,0] -> First column of random_variables (all rows of column 0)

 - random_variables[:,1] -> Second column of random_variables (all rows of column 1)
In [4]:
random_variables = np.random.randn(100, 2)

x = random_variables[:,0]

y = random_variables[:,1]

plt.scatter(x, y)

plt.savefig('scater1.png')

Sample 2

- np.random.randn()

    - Returning samples from standard normal distribution 

    - All points are centered at zero (by default)

- X[:50] += 3 

    - First half of data will be centered at 3

- Y = np.zeros(200)

    - an array with 200 zeros

- Y[:50] = 1

    - Replace first half of zeros with 1 
    - All the points centered at 3 will have label 1
    - Other point will have label 0

- c=Y 

    - c stands for color
    - One dimenstional array containing integer how to color data
In [5]:
X = np.random.randn(200, 2)
X[:50] += 3

Y = np.zeros(200)
Y[:50] = 1


plt.scatter(X[:,0], X[:,1], c=Y)

plt.savefig('scater2.png')

Sample 3

In [6]:
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt

x = []
y = []
k = 2000

while len(x) < k:
    X = randn()
    if -1 <= X <= 1:
        x.append(X)
         
while len(y) < k:
    X = randn()
    if -1 <= X <= 1:
        y.append(X)
        
Y = np.zeros(k)

for i in range(k):
    if x[i]<0:
        if y[i]>0:
            Y[i] = 1
    elif x[i]>0:
        if y[i]<0:
            Y[i] = 1
        else:
            Y[i] = 0

x = np.array(x)
y = np.array(y)        
            
plt.scatter(x, y, c=Y)

plt.savefig('scater3.png')

Histogram

In [7]:
X = np.random.randn(10000)

plt.hist(X, bins=20)

plt.savefig('hist1.png')

Bar Plot

In [21]:
x = [2,8,10] 
y = [11,16,9]  

x2 = [3,9,11] 
y2 = [6,15,7] 

plt.bar(x, y) 
plt.bar(x2, y2, color = 'r') 

plt.title('Bar graph') 
plt.ylabel('Y axis') 
plt.xlabel('X axis')  

plt.show()

Boxplot

In [30]:
np.random.seed(19680801)

all_data = [np.random.normal(0, std, size=100) for std in range(1, 4)]

labels = ['x1', 'x2', 'x3']

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 4))

# rectangular box plot
bplot1 = ax1.boxplot(all_data,
                     vert=True,  # vertical box alignment
                     patch_artist=True,  # fill with color
                     labels=labels)  # will be used to label x-ticks

ax1.set_title('Rectangular box plot')

# notch shape box plot
bplot2 = ax2.boxplot(all_data,
                     notch=True,  # notch shape
                     vert=True,  # vertical box alignment
                     patch_artist=True,  # fill with color
                     labels=labels)  # will be used to label x-ticks

ax2.set_title('Notched box plot')

# fill with colors
colors = ['pink', 'lightblue', 'lightgreen']
for bplot in (bplot1, bplot2):
    for patch, color in zip(bplot['boxes'], colors):
        patch.set_facecolor(color)

# adding horizontal grid lines
for ax in [ax1, ax2]:
    ax.yaxis.grid(True)
    ax.set_xlabel('Three separate samples')
    ax.set_ylabel('Observed values')

plt.show()

Pie Chart

In [45]:
labels = 'Python', 'C++', 'Ruby', 'Java'
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.4, 0, 0, 0)  # explode 1st slice


plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True)

plt.axis('equal')
plt.show()

Plotting Images

In [8]:
from PIL import Image

#url = "https://datascienceschools.github.io/Data_Visualization/cat.jpg"

image = Image.open('cat.jpg')

image
Out[8]:

Converting Jpeg to Numpy Array

In [9]:
photo_array = np.array(image)

Shape of Numpy Array (photo_array)

- (225, 225, 3)

- 225 rows
- 255 columns
- 3 -> color photo RBG
- Every pixel is 3*3
In [10]:
photo_array.shape
Out[10]:
(432, 768, 3)
In [11]:
plt.imshow(photo_array);
In [12]:
gray_photo = photo_array.mean(axis=2)
In [13]:
gray_photo.shape
Out[13]:
(432, 768)
In [14]:
plt.imshow(gray_photo);
In [15]:
plt.imshow(gray_photo, cmap='gray')

plt.savefig('img.png')

Creating Subplots

In [17]:
x=np.arange(0,10)
y=np.arange(11,21)

plt.subplot(2,2,1)
plt.plot(x,y,'r--')

plt.subplot(2,2,2)
plt.plot(x,y,'g*--')

plt.subplot(2,2,3)
plt.plot(x,y,'bo')

plt.subplot(2,2,4)
plt.plot(x,y,'go')

plt.show()