Uploaded by asubadin11

numpy tutorial.matplotlib only

advertisement
import numpy as np
# ------------------------------------------------------# PLOTING NUMPY ARRAY USING MATPLOTLIB
# https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html
# ------------------------------------------------------import matplotlib.pyplot as plt
# basic plotting
x = np.array([0, 1, 2, 3, 4])
plt.figure()
plt.plot(x, 2 * x)
plt.show(block=True)
# plt.close()
#
#
#
#
#
#
preparing horizontal grids
creating a figure
drawing a plot in a figure
(default) If True block and run the GUI main loop
until all figure windows are closed.
close the latest figure
# plotting sinusoids
x2 = np.arange(-1, 1, 0.05) * np.pi
plt.figure(1)
# open a figure and number it as 1
plt.plot(x2, np.sin(x2))
plt.xlabel('radians')
plt.ylabel('sin value')
plt.title('Sin signal')
plt.show(block=False)
# If False ensure that all figure windows are displayed and return immediately.
plt.close(1)
# close the figure 1
# multiple sub-plots in a figure
x2 = np.arange(-1, 1, 0.05) * np.pi
f, axes = plt.subplots(2, 1) # no need to generate plt.figure()
axes[0].plot(x2, np.sin(x2))
axes[0].set_title('sine')
axes[1].plot(x2, 2 * np.cos(x2))
axes[1].set_title('cosine')
plt.show()
#
# multiple plots overlapped in a figure
x2 = np.arange(-1, 1, 0.05) * np.pi
plt.figure()
plt.plot(x2, np.sin(x2))
plt.plot(x2, 2 * np.cos(x2), '--');
plt.legend(['sin', 'cos']);
plt.show()
#
# plt.close('all')
# close all the figures
#--------------------------------------------------# Read and display image using NumPy and MatplotLib
#--------------------------------------------------import matplotlib.pyplot as plt
import numpy as np
import PIL.Image as pilimg
path = './hands-on/'
# Read the image by pilimg.open() which returns ‘PIL.JpegImagePlugin.JpegImageFile’ class.
img = pilimg.open(path+"chest_radiograph.jpg")
#convert ‘PIL.JpegImagePlugin.JpegImageFile’ class into ‘numpy.ndarry’ class
img_ndarray = np.array(img)
plt.figure(0)
plt.imshow(img_ndarray, cmap = 'gray')
# plt.show()
plt.show(block=False) # Execution is not blocked even though the window is not closed.
plt.close(0)
Download