Post

How to handle Data, and Images(18) Matplotlib Intro

Introduction to Matplotlib and how to plot a line graph and save the figure

Lesson Notes in .ipynb file

How to handle Data, and Images(18) - Matplotlib Intro

Topics

Matplotlib Basics

  • Matplotlib is an opensource library that allows to visualize data
  • From simple data analyzation, AI model visualization there’s a lot of usage

Drawing simple line graph

1
2
3
4
5
6
7
8
9
10
11
12
import matplotlib.pyplot as plt

x = [1,2,3]
y = [1,2,3]
# plot the graph
plt.plot(x, y)

# title it 'Line Graph' with label 'X', and 'Y'
plt.title('Line Graph')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

Output:

Basic Line Graph
Desktop View

Saving Graph (1)

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

x = [1,2,3]
y = [1,2,3]
# plot the graph
plt.plot(x, y)

# title it 'Line Graph' with label 'X', and 'Y'
plt.title('Line Graph')
plt.xlabel('X')
plt.ylabel('Y')
# save the figure as 'line_graph.png'
plt.savefig('line_graph.png')

Output:

Basic Line GraphSaved Fig
Desktop ViewDesktop View

Saving Graph(2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt
import numpy as np

# with width pi * 10, make 500 dots equally
x = np.linspace(0, np.pi * 10, 500)
# make 2 graphs
fig, axes = plt.subplots(2, 1)
# 1st graph is sin graph
axes[0].plot(x, np.sin(x))
# 2nd graph is cos graph
axes[1].plot(x, np.cos(x))

# save figure as 'sin&cos.png'
fig.savefig('sin&cos.png')

Output:

Sin & Cos GraphSaved Figure
Desktop ViewDesktop View

Drawing Line Graph (1)

1
2
3
4
5
6
7
8
9
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-9, 10)
y = x ** 2
# as a linestyle we can use '-', ':', '-.' '--' and more 
plt.plot(x, y, linestyle=':', marker='*')

plt.show()

Output:

$y = x^2$
Desktop View

Drawing Line Graph (2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-9, 10)
y1 = x ** 2
y2 = -x

# plot a line graph 'y = x ** 2'
plt.plot(x, y1, linestyle='-.', marker='*', color='red', label='y = x * x')
# plot a line graph 'y = -x'
plt.plot(x, y2, linestyle=':', marker='o', color='blue', label='y= -x')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(
    shadow = True,
    borderpad = 1
)
plt.show()

Output:

Figure
Desktop View

Summary

This post is licensed under CC BY 4.0 by the author.