import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

Matplotlib#

Matplotlib with Pandas#

url_oceania = "https://raw.githubusercontent.com/clemsonciti/intro-to-python/master/data3/gapminder_gdp_oceania.csv"
data_o = pd.read_csv(url_oceania, index_col='country')
data_o
gdpPercap_1952 gdpPercap_1957 gdpPercap_1962 gdpPercap_1967 gdpPercap_1972 gdpPercap_1977 gdpPercap_1982 gdpPercap_1987 gdpPercap_1992 gdpPercap_1997 gdpPercap_2002 gdpPercap_2007
country
Australia 10039.59564 10949.64959 12217.22686 14526.12465 16788.62948 18334.19751 19477.00928 21888.88903 23424.76683 26997.93657 30687.75473 34435.36744
New Zealand 10556.57566 12247.39532 13175.67800 14463.91893 16046.03728 16233.71770 17632.41040 19007.19129 18363.32494 21050.41377 23189.80135 25185.00911
data_o.loc["Australia"].plot()
<Axes: >
../_images/b453ab34002d13e13e2f7f38068e1548467ab834a60ac56bb9d66f4d736f5c66.png
#data_o.columns
#Converting Column names into Integers
years = data_o.columns.str.strip('gdpPercap_').astype(int)
years
Index([1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, 2002, 2007], dtype='int32')
#Renaming column names
data_o.columns = years
data_o
1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 2002 2007
country
Australia 10039.59564 10949.64959 12217.22686 14526.12465 16788.62948 18334.19751 19477.00928 21888.88903 23424.76683 26997.93657 30687.75473 34435.36744
New Zealand 10556.57566 12247.39532 13175.67800 14463.91893 16046.03728 16233.71770 17632.41040 19007.19129 18363.32494 21050.41377 23189.80135 25185.00911
data_o.loc["Australia"].plot()
<Axes: >
../_images/3a63da2a079ff32ef83d4d4b36317d1ee2016ebfe0f6573e2a543370213aa9d8.png
#Changing style of plot
plt.style.use('ggplot')
data_o.T.plot()
plt.ylabel('GDP per capita')
plt.xlabel('Years')
Text(0.5, 0, 'Years')
../_images/147a7782e3590e7085086f32bef90b062356465b1c0ef967dd39a3bd9d3709fe.png
#Another way of plotting
gdp_nz = data_o.loc["New Zealand"]
gdp_aus = data_o.loc["Australia"]
data_o[1987]
country
Australia      21888.88903
New Zealand    19007.19129
Name: 1987, dtype: float64
plt.style.use('default')
plt.plot(years,gdp_aus,"g-.", label="Australia")
plt.plot(years,gdp_nz,"r--", label="New Zealand")
##Plotting one specific point
plt.plot(1987,data_o.loc["Australia",1987],"bx")
#Axis labels
plt.ylabel('GDP per capita')
plt.xlabel('Years')
#adding legend
plt.legend(loc="best")
#plt.xticks(rotation=60)
plt.savefig("oceania.png")
../_images/0bae8eebbfca251ac58fd7bf052eee665f72dbe47a03a433ee74d8746b9869df.png

Other Types of plots: Bar and Scatter Plots#

#Creating example Data
x = np.arange(10)
y = x**2
b1 = ["cats", "dogs", "birds", "fishes"]
b2 = [3,6,2,5]
#s1 = np.arange(10)
s = np.random.randint(2,9,10)
x1 = np.linspace(0, 2*np.pi, 200)
y1 = np.sin(2*(x1**2))
#line plot
plt.plot(x,y, 'b^-')
plt.xlabel("Integer values")
plt.ylabel("xsquared")
Text(0, 0.5, 'xsquared')
../_images/810ccd4487e410f4997a7be22032a1a52cc27ac1d8a9b38a617d49c59a91baf0.png
#Line plot 2
plt.plot(x1,y1, 'r')
[<matplotlib.lines.Line2D at 0x2367b074f90>]
../_images/98f9faa90da26b1e4fc077be0683e51ba0e9673c1cdd1cd55720be2dd4790c78.png
#Bar plots
plt.bar(b1,b2,width=0.5)
plt.xlabel("Pets")
plt.ylabel("No. of Pets")
Text(0, 0.5, 'No. of Pets')
../_images/688e5e4e39c529e50aeb05d8dd019c53961f9a215ed2f1611943b24a0261dc85.png
#Scatter plots
plt.scatter(x,s, c = "green", marker = "*")
plt.xlabel("No. of days")
plt.ylabel("Measured Values")
Text(0, 0.5, 'Measured Values')
../_images/38f40c6c250da8794080d41d07ec5e02c672e630be594341bd2732e1b9b2826e.png

Subplots#

fig, ax = plt.subplots()
#print(ax)
ax.plot(x,y)
ax.plot(x1,y1)
[<matplotlib.lines.Line2D at 0x2367b0ab750>]
../_images/12ceb672f7230e3518677d0b9ddac14a1d83fdf1d91e90c33709c5a5c4678227.png
fig, ax = plt.subplots(2)
#print(ax)
ax[1].plot(x,y, "b^-")
ax[0].plot(x1,y1, 'r')
[<matplotlib.lines.Line2D at 0x2367b0e8f50>]
../_images/e3ea69e672f617729cb3d86203b524d3ec9b0d098795fb506cc92f3d47773e3b.png
fig1, ax1 = plt.subplots(2,2)
#print(fig1, ax1)
ax1[0,0].plot(x,y,"b^-")
ax1[0,0].set_title("p1")
ax1[0,1].plot(x1,y1)
ax1[0,1].set_title("p2")
ax1[1,0].scatter(x,s)
ax1[1,0].set_title("p3")
ax1[1,1].bar(b1,b2)
ax1[1,1].set_title("p4")
fig1.tight_layout()
../_images/699777c755f49104aaffe4cbeccc90f47b779c3a76b6e1f5d1a1729e7c6960cc.png

Other types of plots#

reference: http://www.math.buffalo.edu/~badzioch/MTH337/PT/PT-image_processing/PT-image_processing.html

np.random.seed(2023)
mat2 = np.random.randint(-255,255,65025).reshape(255,255)
#plt.imshow(mat2)
#plt.imshow(mat2, interpolation = "bicubic") ## bilinear, gaussian, lanczos, bicubic
plt.imshow(mat2, interpolation = "bicubic", cmap = 'magma') #cmaps: viridis, plasma, inferno, magma
#plt.colorbar() ##Add colorbar for to show values
<matplotlib.image.AxesImage at 0x2367c345410>
../_images/2896a6b2315625c39dd95a6aa7c2ad80b06f6b814cd63e2c42c4fd2b19bf5cde.png
#!wget https://upload.wikimedia.org/wikipedia/commons/3/3d/Fesoj_-_Papilio_machaon_%28by%29.jpg -O butterfly.JPG
butterfly = plt.imread("butterfly.jpg")
#print(type(butterfly))
#plt.imshow(butterfly)
plt.imshow(butterfly[200:400,350:550], interpolation="lanczos")
<matplotlib.image.AxesImage at 0x2367c3a5410>
../_images/9fabad2146fd2a8b4ad75dd67f1e0d10489fd609d1a6a0ebe9ab0449e736e59a.png

Example: Random Walk#

Solution 1#

def random_walk(num_steps):
    walk = np.zeros(num_steps)
    for step in range(len(walk)):
        #Coin flip result
        coin_flip_result = np.random.randint(2)
        if coin_flip_result == 0:
            #Heads
            walk[step] = walk[step-1]+1
        else:
            #Tails
            walk[step] = walk[step-1]-1
    plt.plot(walk)
%%time
walk_range = 1000
num_steps = 200
for walk in range(walk_range):
    random_walk(num_steps)
CPU times: total: 688 ms
Wall time: 697 ms
../_images/34598dfb98d9e9c5de2bcce71a7df7601d13d842034e8b673236e8b2c5d3e5be.png

Solution 2#

%%time
for walk in range(walk_range):
    plt.plot(np.cumsum([1 if i else -1 for i in np.random.randint(2, size=num_steps)]))
CPU times: total: 297 ms
Wall time: 306 ms
../_images/8e7f0270373534259c02b3d6cc954ae2716f5193c242172688ccf39f84c3dcfc.png