Graph plotting in Python
Dr. Santosh Prasad Gupta
Assistant Professor
Department of Physics
Patna University, Patna
6/24/2021 Department of Physics, PU: SP Gupta 1
In this document we learn about:
Simple plot
Simple plot of 𝒙𝟐 with default setting
Simple plot of 𝒙, 𝒙𝟐 , 𝒙𝟑 with modification
Plot of trigonometric function: 𝒄𝒐𝒔𝒙 𝒂𝒏𝒅 𝒔𝒊𝒏𝒙
Plot of trigonometric function: 𝒕𝒂𝒏𝒙 𝒂𝒏𝒅 𝒄𝒐𝒕𝒙
Subplot: Horizontally and Vertically
Subplot of trigonometric function : 𝒔𝒊𝒏𝒙𝟐 𝒂𝒏𝒅 𝒄𝒐𝒔𝒙𝟐
Scatter plot
Scatter plot of exponential function : 𝐞𝐱𝐩(𝐱)
Contour plot
Contour plot : 𝒁 = 𝑿𝟐 + 𝒚𝟐
Bar plot
Bar plot of a data set by defining a dictionary
6/24/2021 Department of Physics, PU: SP Gupta 2
Graph plotting with Matplotlib
Matplotlib comes with a set of default settings that allow customizing all kinds of
properties. You can control the defaults of almost every property in matplotlib: figure
size and dpi, line width, color and style, axes, axis and grid properties, text and font
properties and so on.
Simple plotting of 𝒙𝟐 with default setting
np.arange(a, b, stepsize)
np.linspace(a, b, number of stepes)
# Simple plotting with default setting
import numpy as np
import matplotlib.pyplot as plt
# evenly sampled space: at 20 intervals
x = np.arange(0, 10, 0.5)
#x = np.linspace(0, 10, 20)
# red dashes, blue squares and green triangles
plt.plot(x, x**2)
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 3
Simple plotting with some modification
Plotting: 𝒙, 𝒙𝟐 , 𝒙𝟑
# Simple plotting with modification
import numpy as np
import matplotlib.pyplot as plt
# evenly sampled space: at 20 intervals
x = np.arange(0, 10, 0.5)
#x = np.linspace(0, 10, 20)
# red dashes, blue squares and green triangles
plt.plot(x, x, 'r--', label="x")
plt.plot(x, x**2, 'bs',label="x^2")
plt.plot(x, x**3, 'g^', label="x^3")
plt.legend(loc='upper left')
plt.title("Simple plotting")
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 4
Plotting trigonometric function with Matplotlib
Plotting trigonometric function 𝒄𝒐𝒔𝒙 𝒂𝒏𝒅 𝒔𝒊𝒏𝒙
# plotting with default setting
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C)
plt.plot(X, S)
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 5
Changing colors and line widths
...
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
...
# plotting with Changing colors and line widths
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 6
Setting limits of x and y axis
...
plt.xlim(X.min() * 1.2, X.max() * 1.3)
plt.ylim(C.min() * 1.5, C.max() * 1.4)
...
# plotting with modification
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.xlim(X.min() * 1.2, X.max() * 1.3)
plt.ylim(C.min() * 1.5, C.max() * 1.4)
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 7
Setting tick labels
Ticks are now properly placed but their label is not very explicit. We could guess that
3.142 is π but it would be better to make it explicit. When we set tick values, we can
also provide a corresponding label in the second argument list. Note that we’ll use latex
to allow for nice rendering of the label. ...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-pi$', r'$-pi/2$', r'$0$', r'$+pi/2$', r'$+pi$'])
plt.yticks([-1, 0, +1],
# plotting with default setting [r'$-1$', r'$0$', r'$+1$'])
import numpy as np ...
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.xlim(X.min() * 1.2, X.max() * 1.3)
plt.ylim(C.min() * 1.5, C.max() * 1.4)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-pi$', r'$-pi/2$', r'$0$', r'$+pi/2$', r'$+pi$'])
plt.yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 8
Adding legend and title
...
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
plt.legend(loc='upper left')
plt.title("Trigonometry function plot")
…
# plotting with modification
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
plt.legend(loc='upper left')
plt.title("Trigonometry function plot")
plt.xlim(X.min() * 1.2, X.max() * 1.3)
plt.ylim(C.min() * 1.5, C.max() * 1.4)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-pi$', r'$-pi/2$', r'$0$', r'$+pi/2$', r'$+pi$'])
plt.yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 9
Including grid and x and y label in graph
# plotting with modification
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
plt.legend(loc='upper left')
plt.title("Trigonometry function plot")
plt.xlim(X.min() * 1.2, X.max() * 1.3)
plt.ylim(C.min() * 1.5, C.max() * 1.4)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-pi$', r'$-pi/2$', r'$0$', r'$+pi/2$', r'$+pi$'])
plt.yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
plt.xlabel("X axis label")
plt.ylabel("Y axis label")
plt.grid(True)
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 10
Plotting of Tan and Cot function
Plotting of 𝒕𝒂𝒏𝒙 𝒂𝒏𝒅 𝒄𝒐𝒕 𝒙
# plotting tan and cot function
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.tan(X), np.tan(X)
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="tan")
plt.plot(X, 1/S, color="red", linewidth=2.5, linestyle="-", label="cot")
plt.legend(loc='upper left')
plt.title("Trigonometry function plot")
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(C.min() * 1.1, C.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-pi$', r'$-pi/2$', r'$0$', r'$+pi/2$', r'$+pi$'])
#plt.yticks([-1, 0, +1],
#[r'$-1$', r'$0$', r'$+1$'])
plt.grid(True)
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 11
Sub plot: Vertically stacked subplots
Subplot: 𝒔𝒊𝒏𝒙𝟐 𝒂𝒏𝒅 𝒄𝒐𝒔𝒙𝟐
# subplot tutorial
import matplotlib.pyplot as plt
import numpy as np
# Some example data to display
x = np.linspace(0, 2*np.pi, 400)
y1 = np.sin(x**2)
y2 = np.cos(x**2)
fig, (san1, san2) = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
san1.plot(x, y1, color="blue", linewidth=2.5, linestyle="-", label="sinx^2")
san2.plot(x, y2, color="green", linewidth=2.5, linestyle="-", label="cosx^2")
san1.legend(loc='upper left')
san2.legend(loc='upper left')
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 12
Sub plot: Horizontally stacked subplots
Subplot: 𝒔𝒊𝒏𝒙𝟐 𝒂𝒏𝒅 𝒄𝒐𝒔𝒙𝟐
# subplot tutorial
import matplotlib.pyplot as plt
import numpy as np
# Some example data to display
x = np.linspace(0, 2*np.pi, 400)
y1 = np.sin(x**2)
y2 = np.cos(x**2)
fig, (san1, san2) = plt.subplots(1, 2)
fig.suptitle(‘Horizontally stacked subplots')
san1.plot(x, y1, color="blue", linewidth=2.5, linestyle="-", label="sinx^2")
san2.plot(x, y2, color="green", linewidth=2.5, linestyle="-", label="cosx^2")
san1.legend(loc='upper left')
san2.legend(loc='upper left')
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 13
Scatter plot:
𝒆𝒙𝒑(𝒙)
#scatter plot tutorial
import matplotlib.pyplot as plt
import numpy as np
# Some example data to display
x = np.linspace(0, 2*np.pi, 40)
y = np.exp(x)
plt.scatter(x, y, color='green', label="exp")
plt.legend(loc='upper left')
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 14
Contour Plot: 𝒁 = 𝑿 𝟐 + 𝒚𝟐
# contour plot tutorial
import matplotlib.pyplot as plt
import numpy as np
start, stop, n_values = -8, 8, 800
x_vals = np.linspace(start, stop, n_values)
y_vals = np.linspace(start, stop, n_values)
X, Y = np.meshgrid(x_vals, y_vals)
Z = np.sqrt(X**2 + Y**2)
cp = plt.contourf(X, Y, Z, 20, cmap=“BrBG”)
plt.colorbar(cp)
plt.title('Contour Plot')
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 15
Bar Plot:
import numpy as np
import matplotlib.pyplot as plt
# creating the dataset
data = {'C':20, 'C++':15, 'Java':30, 'Python':35}
courses = list(data.keys())
values = list(data.values())
# creating the dataset
plt.figure(figsize = (5, 5))
# creating the bar plot
plt.bar(courses, values, color =‘blue', width = 0.4)
# Labeling the X and Y axis
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()
6/24/2021 Department of Physics, PU: SP Gupta 16
Assignments:
Question 1: Write a python script to plot 𝒙𝟑 + 𝒆𝒙𝒑 −𝒙 − 𝟏/𝒙𝟐
Question 2: Write a python script to plot the trigonometric
function: 𝒔𝒆𝒄𝒙 𝑎𝑛𝑑 𝒄𝒐𝒔𝒆𝒄𝒙
Question 3: Write a python script for subplot of function 𝒔𝒆𝒄𝒙 and 𝟏/𝒙
Question 4: Write a python script for contour plot of function
𝒁 = 𝒔𝒊𝒏𝒙 + 𝒔𝒊𝒏𝒚
Question 5: Write a python script to define the dictionary where
months of a year are the keys and number of days in each month are
the corresponding values. And show the bar plot for the dictionary.
6/24/2021 Department of Physics, PU: SP Gupta 17