Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
80 views

Matplotlib - Ipynb - Colaboratory

Uploaded by

ashfaashraf9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

Matplotlib - Ipynb - Colaboratory

Uploaded by

ashfaashraf9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

3/14/24, 10:20 AM matplotlib.

ipynb - Colaboratory

#MATPLOTLIB EXERCISE

keyboard_arrow_down USPCAS-E NUST


Thermal Energy Engineering
Dr. Majid Ali

import matplotlib.pyplot as plt


x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.bar(x_pos, popularity, color='blue')
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("Popularity of Programming Language\n" + "Worldwide, Oct 2017 compared to a year ago")
plt.xticks(x_pos, x)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='gray')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()

import matplotlib.pyplot as plt


x = ['Java', 'Python', 'PHP', 'JS', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.barh(x_pos, popularity, color='green')
plt.xlabel("Popularity")
plt.ylabel("Languages")
plt.title("Popularity of Programming Language\n" + "Worldwide, Oct 2017 compared to a year ago")
plt.yticks(x_pos, x)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 1/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import matplotlib.pyplot as plt


x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]

plt.bar(x_pos, popularity, color=['red', 'black', 'green', 'blue', 'yellow', 'cyan'])

plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017 compared to a year ago")
plt.xticks(x_pos, x)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 2/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
import numpy as np
import matplotlib.pyplot as plt

# data to plot
n_groups = 5
men_means = (22, 30, 33, 30, 26)
women_means = (25, 32, 30, 35, 29)

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, men_means, bar_width,


alpha=opacity,
color='g',
label='Men')

rects2 = plt.bar(index + bar_width, women_means, bar_width,


alpha=opacity,
color='r',
label='Women')

plt.xlabel('Person')
plt.ylabel('Scores')
plt.title('Scores by person')
plt.xticks(index + bar_width, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.legend()

plt.tight_layout()
plt.show()

from pandas import DataFrame


import matplotlib.pyplot as plt
import numpy as np

a=np.array([[4,8,5,7,6],[2,3,4,2,6],[4,7,4,7,8],[2,6,4,8,6],[2,4,3,3,2]])
df=DataFrame(a, columns=['a','b','c','d','e'], index=[2,4,6,8,10])

df.plot(kind='bar')
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='green')
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')

plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 3/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (54.74, 42.35, 67.37, 58.24, 30.25)
menStd = (4, 3, 4, 1, 5)
# the x locations for the groups
ind = np.arange(N)
# the width of the bars
width = 0.35
plt.bar(ind, menMeans, width, yerr=menStd, color='red')
plt.ylabel('Scores')
plt.xlabel('Velocity')
plt.title('Scores by Velocity')
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='green')
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 4/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (22, 30, 35, 35, 26)
womenMeans = (25, 32, 30, 35, 29)
menStd = (4, 3, 4, 1, 5)
womenStd = (3, 5, 2, 3, 3)
# the x locations for the groups
ind = np.arange(N)
# the width of the bars
width = 0.35

p1 = plt.bar(ind, menMeans, width, yerr=menStd, color='red')


p2 = plt.bar(ind, womenMeans, width,
bottom=menMeans, yerr=womenStd, color='green')

plt.ylabel('Scores')
plt.xlabel('Groups')
plt.title('Scores by group\n' + 'and gender')
plt.xticks(ind, ('Group1', 'Group2', 'Group3', 'Group4', 'Group5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 5/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
import numpy as np
import matplotlib.pyplot as plt

people = ('G1','G2','G3','G4','G5','G6','G7','G8')
segments = 4

# multi-dimensional data
data = [[ 3.40022085, 7.70632498, 6.4097905, 10.51648577, 7.5330039,
7.1123587, 12.77792868, 3.44773477],
[ 11.24811149, 5.03778215, 6.65808464, 12.32220677, 7.45964195,
6.79685302, 7.24578743, 3.69371847],
[ 3.94253354, 4.74763549, 11.73529246, 4.6465543, 12.9952182,
4.63832778, 11.16849999, 8.56883433],
[ 4.24409799, 12.71746612, 11.3772169, 9.00514257, 10.47084185,
10.97567589, 3.98287652, 8.80552122]]
percentages = (np.random.randint(5,20, (len(people), segments)))
y_pos = np.arange(len(people))

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)

colors ='rgwm'
patch_handles = []
# left alignment of data starts at zero
left = np.zeros(len(people))
for i, d in enumerate(data):
patch_handles.append(ax.barh(y_pos, d,
color=colors[i%len(colors)], align='center',
left=left))
left += d

# search all of the bar segments and annotate


for j in range(len(patch_handles)):
for i, patch in enumerate(patch_handles[j].get_children()):
bl = patch.get_xy()
x = 0.5*patch.get_width() + bl[0]
y = 0.5*patch.get_height() + bl[1]
ax.text(x,y, "%d%%" % (percentages[i,j]), ha='center')

ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Scores')
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 6/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import matplotlib.pyplot as plt


fig = plt.figure()
patterns = [ "|" , "\\" , "/" , "+" , "-", ".", "*","x", "o", "O" ]

ax = fig.add_subplot(111)
for i in range(len(patterns)):
ax.bar(i, 3, color='white', edgecolor='black', hatch=patterns[i])

plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 7/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import matplotlib.pyplot as plt


# line 1 points
x1 = [10,20,30]
y1 = [20,40,10]
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Two or more lines with different widths and colors with suitable legends ')
# Display the figure.
plt.plot(x1,y1, color='blue', linewidth = 3, label = 'line1-width-3')
plt.plot(x2,y2, color='red', linewidth = 5, label = 'line2-width-5')
# show a legend on the plot
plt.legend()
plt.show()

import matplotlib.pyplot as plt


# line 1 points
x1 = [10,20,30]
y1 = [20,40,10]
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Plot lines and/or markers to the Axes.
plt.plot(x1,y1, color='blue', linewidth = 3, label = 'line1-dotted',linestyle='dotted')
plt.plot(x2,y2, color='red', linewidth = 5, label = 'line2-dashed', linestyle='dashed')
# Set a title
plt.title("Plot with two or more lines with different styles")
# show a legend on the plot
plt.legend()
# function to show the plot
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 8/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import matplotlib.pyplot as plt


# x axis values
x = [1,4,5,6,7]
# y axis values
y = [2,6,3,6,3]

# plotting the points


plt.plot(x, y, color='red', linestyle='dashdot', linewidth = 3,
marker='o', markerfacecolor='blue', markersize=12)
#Set the y-limits of the current axes.
plt.ylim(1,8)
#Set the x-limits of the current axes.
plt.xlim(1,8)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('Display marker')
# function to show the plot
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 9/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
import numpy as np
import pylab as pl
# Make an array of x values
x1 = [2, 3, 5, 6, 8]
# Make an array of y values for each x value
y1 = [1, 5, 10, 18, 20]
# Make an array of x values
x2 = [3, 4, 6, 7, 9]
# Make an array of y values for each x value
y2 = [2, 6, 11, 20, 22]
# set new axes limits
pl.axis([0, 10, 0, 30])
# use pylab to plot x and y as red circles
pl.plot(x1, y1,'b*', x2, y2, 'ro')
# show the plot on the screen
pl.show()

import numpy as np
import matplotlib.pyplot as plt

# Sampled time at 200ms intervals


t = np.arange(0., 5., 0.2)

# green dashes, blue squares and red triangles


plt.plot(t, t, 'g--', t, t**2, 'bs', t, t**3, 'r^')
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 10/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num

data = [(DT.datetime.strptime('2016-10-03', "%Y-%m-%d"), 772.559998),


(DT.datetime.strptime('2016-10-04', "%Y-%m-%d"), 776.429993),
(DT.datetime.strptime('2016-10-05', "%Y-%m-%d"), 776.469971),
(DT.datetime.strptime('2016-10-06', "%Y-%m-%d"), 776.859985),
(DT.datetime.strptime('2016-10-07', "%Y-%m-%d"), 775.080017 )]

x = [date2num(date) for (date, value) in data]


y = [value for (date, value) in data]

fig = plt.figure()

graph = fig.add_subplot(111)

# Plot the data as a red line with round markers


graph.plot(x,y,'r-o')

# Set the xtick locations


graph.set_xticks(x)

# Set the xtick labels


graph.set_xticklabels(
[date.strftime("%Y-%m-%d") for (date, value) in data]
)

# naming the x axis


plt.xlabel('Date')
# naming the y axis
plt.ylabel('Closing Value')
# giving a title
plt.title('Closing stock value of Alphabet Inc.')
# Turn on the minor TICKS, which are required for the minor GRID
plt.minorticks_on()

# Customize the major grid


plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')

# Turn off the display of all ticks.


plt.tick_params(which='both', # Options for both major and minor ticks
top='off', # turn off top ticks
left='off', # turn off left ticks
right='off', # turn off right ticks
bottom='off') # turn off bottom ticks
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 11/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
import matplotlib.pyplot as plt
from pylab import randn
X = randn(200)
Y = randn(200)
plt.scatter(X,Y, color='r')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

import matplotlib.pyplot as plt


import numpy as np
x = np.random.randn(50)
y = np.random.randn(50)
plt.scatter(x, y, s=70, facecolors='none', edgecolors='g')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 12/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
import math
import random
import matplotlib.pyplot as plt
# create random data
no_of_balls = 25
x = [random.triangular() for i in range(no_of_balls)]
y = [random.gauss(0.5, 0.25) for i in range(no_of_balls)]
colors = [random.randint(1, 4) for i in range(no_of_balls)]
areas = [math.pi * random.randint(5, 15)**2 for i in range(no_of_balls)]
# draw the plot
plt.figure()
plt.scatter(x, y, s=areas, c=colors, alpha=0.85)
plt.axis([0.0, 1.0, 0.0, 1.0])
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

import matplotlib.pyplot as plt


import pandas as pd
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
plt.scatter(marks_range, math_marks, label='Math marks', color='r')
plt.scatter(marks_range, science_marks, label='Science marks', color='g')
plt.title('Scatter Plot')
plt.xlabel('Marks Range')
plt.ylabel('Marks Scored')
plt.legend()
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 13/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import matplotlib.pyplot as plt


# Data to plot
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
# explode 1st slice
explode = (0.1, 0, 0, 0,0,0)
# Plot
plt.pie(popuratity, explode=explode, labels=languages, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)

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

import matplotlib.pyplot as plt


# Plot data
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
#colors = ['red', 'gold', 'yellowgreen', 'blue', 'lightcoral', 'lightskyblue']
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
# explode 1st slice
explode = (0.1, 0, 0, 0, 0, 0)
# Plot
plt.pie(popuratity, explode=explode, labels=languages, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("Popularity of Programming Language\n" + "Worldwide, Oct 2017 compared to a year ago", bbox={'facecolor':'0.8', 'pad':5})
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 14/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import matplotlib.pyplot as plt


# Plot data
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
#colors = ['red', 'gold', 'yellowgreen', 'blue', 'lightcoral', 'lightskyblue']
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
# explode 1st slice
explode = (0.1, 0, 0, 0, 0, .1)
# Plot
plt.pie(popuratity, explode=explode, labels=languages, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017 compared to a year ago", bbox={'facecolor':'0.8', 'pad':5})
plt.show()

import matplotlib.pyplot as plt


import pandas as pd
df = pd.read_csv('medal.csv')
country_data = df["country"]
medal_data = df["gold_medal"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
explode = (0.1, 0, 0, 0, 0)
plt.pie(medal_data, labels=country_data, explode=explode, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("Gold medal achievements of five most successful\n"+"countries in 2016 Summer Olympics")
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 15/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
import pylab as plt
import numpy as np

x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)
y2 = 0.8 * np.sin(4 * np.pi * x)

fig, (ax1, ax2, ax3) = plt.subplots(


3, 1, sharex=True, figsize=(6, 6))

ax1.fill_between(x, y1)
ax1.set_title('fill between y1 and 0')

ax2.fill_between(x, y1, 1)
ax2.set_title('fill between y1 and 1')

ax3.fill_between(x, y1, y2)


ax3.set_title('fill between y1 and y2')
ax3.set_xlabel('x')
fig.tight_layout()

import pylab as plt


import numpy as np

X = np.linspace(0, 3, 200)
Y1 = X**2 + 3
Y2 = np.sin(X)
Y3 = np.cos(X)

plt.plot(X, Y1, lw=4)


plt.plot(X, Y2, lw=4)
plt.plot(X, Y3, lw=4)

plt.fill_between(X, Y1, Y2, color='k', alpha=.5)


plt.fill_between(X, Y1, Y3, color='y', alpha=.5)

plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 16/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import matplotlib.pyplot as plt

x = [1, 2, 1, 0]
y = [2, 1, 0, 1]

plt.fill(x, y)
plt.show()

# importing package
import matplotlib.pyplot as plt
import numpy as np

# create data
x = [1,2,3,4,5]
y = [3,3,3,3,3]

# plot lines
plt.plot(x, y, label = "line 1", linestyle="-")
plt.plot(y, x, label = "line 2", linestyle="--")
plt.plot(x, np.sin(x), label = "curve 1", linestyle="-.")
plt.plot(x, np.cos(x), label = "curve 2", linestyle=":")
plt.legend()
plt.show()

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 17/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

import matplotlib.pyplot as plt

import numpy as np
import pandas as pd
import seaborn as sns

# set random seed so that you could have the exactly same results as mine.
np.random.seed(0)

df = pd.DataFrame(data={'a':np.random.randint(0, 100, 30),


'b':np.random.randint(0, 100, 30),
'c':np.random.randint(0, 100, 30)})
df.head()

a b c

0 44 47 17

1 47 64 79

2 64 82 4

3 67 99 42

4 67 88 58

# Let's create a figure and call it fig.


fig = plt.figure()
# This will return an empty figure.

<Figure size 640x480 with 0 Axes>

# Let's create a figure with figsize (15, 8) and also call it fig (thus overwriting the reference to the previous fig).
# The 15x8 figsize is arbitrary, but I use it as a standard size to work with for visibility.
fig = plt.figure(figsize=(15,8))

<Figure size 1500x800 with 0 Axes>

fig = plt.figure(figsize=(8,8))
ax = plt.subplot(1,1,1) # (rows, columns, and location)
# this would create a 1x1 grid of subplots
# and choose axes #1

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 18/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

fig = plt.figure(figsize=(8,8))
ax1 = plt.subplot(2,1,1) # this would create a 2x1 grid of subplots
# and choose axes #1
ax2 = plt.subplot(2,1,2) # this would create a 2x1 grid of subplots
# and choose axes #2

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 19/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

fig, ax = plt.subplots(2, 1, figsize=(8,8)) # This creates a figure of size 15x8 with


# a 2x1 grid of subplots.

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 20/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
fig, ax = plt.subplots(2, 1, figsize=(8,8)) # This creates a figure of size 15x8 with
# a 2x1 grid of subplots.
ax[0] # The top axes
ax[1] # The bottom axes

<Axes: >

fig, ax = plt.subplots(2, 2, figsize=(15,8)) # This creates a figure of size 15x8 with


# a 2x1 grid of subplots.

ax[0][0].plot(df.index.values, df['a']) # The top-left axes


ax[0][1].plot(df.index.values, df['b']) # The top-right axes
ax[1][0].plot(df.index.values, df['c']) # The bottom-left axes
ax[1][1].plot(df.index.values, range(len(df))) # The bottom-right axes

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 21/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

[<matplotlib.lines.Line2D at 0x7c578d1d6050>]

fig, ax = plt.subplots(1,1, figsize=(15,8))

x = df.index.values # The index the dataframe we created up above. Equivalent to [0, 1, ..., 28, 29]
y = df['a'] # Column 'a' from df.

ax.plot(x, y)

[<matplotlib.lines.Line2D at 0x7c578d207880>]

# The above plot can be generated without creating the variables


# x and y by passing the values directly to the function.

fig, ax = plt.subplots(2,1, figsize=(15,8))

ax[0].plot(df.index.values, df['a'])
ax[1].plot(df.index.values, df['b'])

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 22/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

[<matplotlib.lines.Line2D at 0x7c578d3fdcf0>]

fig, ax = plt.subplots(1,1, figsize=(15,8))

x = df.index.values # The index the dataframe we created up above. Equivalent to [0, 1, ..., 28, 29]
y1 = df['a'] # Column 'a' from df.
y2 = df['b'] # Column 'a' from df.

ax.plot(x, y1)
ax.plot(x, y2)

[<matplotlib.lines.Line2D at 0x7c578ce79a20>]

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 23/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
sns.set_style('darkgrid') # setting the plotting style
# we only need to call this once,
# usually before we start plotting.

fig, ax = plt.subplots(1,1, figsize=(15,8))

ax.plot(df.index.values, df['a'])
ax.plot(df.index.values, df['b'])

[<matplotlib.lines.Line2D at 0x7c57a0fcef80>]

sns.set_style('darkgrid') # setting the plotting style

fig, ax = plt.subplots(1,1, figsize=(15,8))

ax.plot(df.index.values, df['a'], color='red', ls='-.')


ax.plot(df.index.values, df['b'], color='orange', lw=10)
ax.plot(df.index.values, df['c'], color='yellow', lw=1, marker='o')

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 24/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

[<matplotlib.lines.Line2D at 0x7c578cdc8670>]

fig, ax = plt.subplots(1,1, figsize=(15,8))

ax.plot(df.index.values, df['a'], label='Line A') # add the label


ax.plot(df.index.values, df['b'], label='Line B') # kwarg to each
ax.plot(df.index.values, df['c'], label='Line C') # function

ax.legend(loc='best') # and now call the ax.legend() function


# it will read all of the labels from graphical
# objects under ax

<matplotlib.legend.Legend at 0x7c578d2d6b60>

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 25/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory
fig, ax = plt.subplots(3,1, figsize=(15,8))

ax[0].plot(df.index.values, df['a'], label='Line A') # Top


ax[1].plot(df.index.values, df['b'], label='Line B') # Middle
ax[2].plot(df.index.values, df['c'], label='Line C') # Bottom

ax[0].legend(loc=4) # This will create a legend for ax[0] in the bottom-right.


ax[1].legend(loc=6) # This will create a legend for ax[1] centre-left.

# Also note that all lines will default to the first color in the default color cycle--blue.

<matplotlib.legend.Legend at 0x7c578cceef20>

# My Sample Answer
fig, ax = plt.subplots(2, 1, figsize=(15,8))

ax[0].plot(df.index.values, df['a'], c='green')


ax[0].plot(df.index.values, df['b'], c='orange')
ax[0].legend(loc=9) # "9": upper center

ax[1].plot(df.index.values, df['c'], marker='o', lw=0) # set line width = 0, means no visuable line

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 26/27
3/14/24, 10:20 AM matplotlib.ipynb - Colaboratory

WARNING:matplotlib.legend:No artists with labels found to put in legend. Note that arti
[<matplotlib.lines.Line2D at 0x7c578cc5d6c0>]

fig, ax = plt.subplots(1, 1, figsize=(15,8))

bar_kwargs = {'color':'tomato', 'alpha':0.5}

ax.bar(df.index.values, df['a'], label='a', **bar_kwargs)


ax.legend()

<matplotlib.legend.Legend at 0x7c578cbd8dc0>

# My Sample Answer
fig, ax = plt.subplots(3, 1, figsize=(15,18))

ax[0].bar(df.index.values, df['a'])
for i in range(df.shape[0]):
ax[0] text(i df['a'][i]+1 df['a'][i] horizontalalignment 'center')

https://colab.research.google.com/drive/1W7C-HMEetAs-PkcHrbHJU1HnCvfUIzQ8#printMode=true 27/27

You might also like