0% found this document useful (0 votes)
15 views

PChem3 Python Tutorial6

The document discusses various plotting techniques using the matplotlib module in Python, including line plots, scatter plots, error bars, 3D plots, subplots, and colorbars. Code examples are provided for each technique along with the output figures generated.

Uploaded by

Suhyun Lee
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)
15 views

PChem3 Python Tutorial6

The document discusses various plotting techniques using the matplotlib module in Python, including line plots, scatter plots, error bars, 3D plots, subplots, and colorbars. Code examples are provided for each technique along with the output figures generated.

Uploaded by

Suhyun Lee
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/ 7

Physical Chemistry 3 Spring 2024, SNU

2.6 Plotting graphs


2.6.1 matplotlib module
The matplotlib module provides powerful plotting tools in Python. In this section, I won’t delve into
the details of the functions and options I used. These examples serve as references for your own plots.
As always, if you want to create something different, you can search for it online. Someone has likely
asked a similar question on the internet before. You can find the official documentation here: https:
//matplotlib.org/stable/index.html.

Code 2.113: Matplotlib version, and setting with plt.rc.


1 # !pip install matplotlib
2 import matplotlib
3 import matplotlib.pyplot as plt
4
5 print('Current matplotlib version is:', matplotlib.__version__)
6
7 # Only if you have installed texlive in your machine
8 plt.rc('text', usetex = True)
9 plt.rc('font', family = 'serif')
10 plt.rc('font', size = 11)

Output 2.113

Current matplotlib version is: 3.8.3

matplotlib.pyplot.rc (runtime configutation) contains the default plot style for that runtime. In this
section, we specified the font type and size and enabled LATEX.

62
Physical Chemistry 3 Spring 2024, SNU

2.6.2 Line plots

Code 2.114: Trigonometric functions.


1 import numpy as np
2
3 x = np.linspace(0, 2 * np.pi, 100)
4 y1 = np.sin(x)
5 y2 = np.cos(x)
6 plt.plot(x, y1, 'r-', linewidth = 2, label = 'sine function')
7 plt.plot(x, y2, 'b-', linewidth = .75, label = 'cosine function')
8 plt.hlines(y = 0, xmin = 0, xmax = 2 * np.pi, color = 'lightgray', linestyle = '--', linewidth = 1)
9 plt.xlabel(r'$x$')
10 plt.ylabel(r'$y$')
11 plt.legend(loc = 'lower left')
12 plt.grid(True, color = 'red', alpha = .6, linestyle = '-.', linewidth = .25)
13 plt.title('Trigonometric functions')
14 plt.show()
15 plt.savefig('trigonometrics.png')

Output 2.114

<Figure>

Figure 2.6: Output for Code 2.114.

63
Physical Chemistry 3 Spring 2024, SNU

2.6.3 Scatter plots

Code 2.115: Scatter plot example.


1 x = np.random.rand(1000)
2 y = np.random.rand(1000)
3 colors = np.random.rand(1000)
4
5 plt.scatter(x, y, c = colors, s = 10, alpha = .5, cmap = 'jet')
6 plt.title('Scatter plot')
7 plt.colorbar()
8 plt.show()

Output 2.115

<Figure>

Figure 2.7: Output for Code 2.115.

64
Physical Chemistry 3 Spring 2024, SNU

2.6.4 Inserting error bars

Code 2.116: Error bar example.


1 x = np.linspace(0, 4, 25)
2 y = -x ** 2 + 4 * x
3 yerr = np.random.rand(25)
4
5 plt.errorbar(x, y, yerr, alpha = .5, fmt = 'k.', capsize = 3, capthick = .5)
6 plt.scatter(x, y, s = 25, marker = 'x', alpha = .75)
7 plt.title('Scatter plot with errorbars')
8 plt.show()

Output 2.116

<Figure>

Figure 2.8: Output for Code 2.116.

65
Physical Chemistry 3 Spring 2024, SNU

2.6.5 3D plots

Code 2.117: 3D surface plot example.


1 from mpl_toolkits.mplot3d import axes3d
2 import matplotlib.pyplot as plt
3
4 X, Y = np.linspace(0, 1, 1000), np.linspace(0, 1, 1000)
5 XX, YY = np.meshgrid(X, Y)
6 sigma = 1.
7 ZZ = np.exp(- (np.sqrt((XX ** 2 + YY ** 2)) - 0.5) ** 2 / (2 * (sigma ** 2))) / np.sqrt(2. * np.pi * (
sigma ** 2))
8
9 fig = plt.figure(figsize = (12, 10))
10 ax = fig.add_subplot(projection='3d')
11 ax.set_xlabel(r'$X$')
12 ax.set_ylabel(r'$Y$')
13 ax.set_zlabel(r'$Z$')
14 ax.set_title('3D plot example')
15 surface = ax.plot_surface(XX, YY, ZZ, cmap = plt.get_cmap('viridis'))
16 fig.colorbar(surface, ax = ax, shrink = 0.5)
17
18 plt.show()

Output 2.117

<Figure>

Figure 2.9: Output for Code 2.117.

66
Physical Chemistry 3 Spring 2024, SNU

2.6.6 Subplots

Code 2.118: Subplots example.


1 fig, axes = plt.subplots(2, 4)
2 fig.set_size_inches(12, 4)
3 plt.subplots_adjust(wspace = 0.3, hspace = 0.3)
4
5 x = np.linspace(0, np.pi, 1000)
6
7 for k, idx in zip(range(0,8), range(1, 9)):
8 t = k * np.pi / 4
9 q = np.sin(x) * np.cos(t)
10 plt.subplot(2, 4, idx)
11 plt.xlim(0, np.pi)
12 plt.ylim(-1.2, 1.2)
13 plt.plot(x, q, 'k-', label=k)
14 plt.legend(loc='upper right')
15
16 plt.show()

Output 2.118

<Figure>

Figure 2.10: Output for Code 2.118.

67
Physical Chemistry 3 Spring 2024, SNU

2.6.7 Inserting colorbars

Code 2.119: Colorbar example.


1 from matplotlib.cm import ScalarMappable
2
3 cmap = 'jet'
4 x = np.linspace(0, 2 * np.pi, 300)
5
6 def translated_sine(x, t):
7 return np.sin(x - t)
8
9 fig, ax = plt.subplots(figsize = (8, 6))
10
11 for i, t in enumerate(np.linspace(0, np.pi, 20)):
12 plt.plot(x, translated_sine(x, t), linewidth = 1,
13 color = plt.get_cmap(cmap)(i / 20))
14
15 norm = plt.Normalize(0, np.pi)
16 sm = ScalarMappable(cmap = cmap, norm = norm)
17 sm.set_array([])
18 cbar = plt.colorbar(sm, ax = ax, label = 'Translation')
19
20 plt.xlabel(r'$x$')
21 plt.ylabel(r'$y$')
22 plt.ylim(-1.5, 1.5)
23 plt.title(r'$y = \sin(x-t),\;t\in [0,\pi]$')
24 plt.show()

Output 2.119

<Figure>

Figure 2.11: Output for Code 2.119.

68

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy