# [PYTHON] How to use Matplotlib

## Preparation

#### plot_figure.py


import numpy as np
import matplotlib.pyplot as plt


## plot function

Used for line graphs and scatter plots on planes

Line graph

#### plot_figure.py


x = np.arange(-3,3,0.1)
y = np.sin(x)
plt.plot(x,y)
plt.show()


Graph the value of sin when => x = -3,3,0.1

--np.arange creates a sequence of numbers on the x-axis --The first argument of the plot function is the x-axis and the second argument is the y-axis. --Draw a graph with show ()

Scatter plot

#### plot_figure.py


x = np.random.randint(0,10,30)
y = np.sin(x) + np.random.randint(0,10,30)
plt.plot(x,y,"o")
plt.show()


--The third argument "o" of plot () is a small circle marker -You can also use "ro" to make it a red marker.

## hist function

Draw a histogram

#### plot_fugure.py


plt.hist(np.random.randn(1000))
plt.show()


## Title => title function

#### plot_figure.py


plt.hist(np.random.randn(1000))
plt.title("Histgram")
plt.show()


## y-axis range => ylim function

#### plot_figure.py


x = np.arange(0,10,0.1)
y = np.exp(x)
plt.plot(x,y)
plt.title("exponential function $y = e^x$")
plt.ylim(0,5000) #0 on y axis~Designated in the range of 5000
plt.show()


## Draw dashed line => hlines function

To draw multiple graphs in the same area, simply call them twice. Draw a straight line with y = -1, y = 1 with the hlines function

#### plot_figure.py


xmin, xmax = -np.pi, np.pi
x = np.arange(xmin, xmax, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.hlines([-1, 1], xmin, xmax, linestyles="dashed")  # y=-1,Draw a dashed line on 1
plt.title(r"$\sin(x)$ and $\cos(x)$")
plt.xlim(xmin, xmax)
plt.ylim(-1.3, 1.3)
plt.show()


## Draw separate graphs in one figure => subplot function

Specify the number of rows, columns, and plot number of the plot you want to fit in one figure

plt.subplot(Number of rows, number of columns, number of plots)


Let's divide the two functions in the previous figure into upper and lower parts. Since it is divided into upper and lower parts, the number of lines is 2. The number of columns is 1

#### plot_figure.py


xmin, xmax = -np.pi, np.pi
x = np.arange(xmin, xmax, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

#sin plot
plt.subplot(2,1,1)
plt.plot(x,y_sin)
plt.title(r"$\sin x$")
plt.xlim(xmin,xmax)
plt.ylim(-1.3,1.3)

#cos plot
plt.subplot(2,1,2)
plt.plot(x,y_cos)
plt.title(r"$\cos x$")
plt.xlim(xmin,xmax)
plt.ylim(-1.3,1.3)

plt.tight_layout() #Prevent title cover
plt.show()


--You can also write subplot (221) instead of subplot (2,1,1)

## reference

I studied with reference to Introduction to matplotlib.