개요
line
import matplotlib.pyplot as plt
plt.plot([-1,-4.5,16,23])
plt.show()
point
import matplotlib.pyplot as plt
plt.plot([-1,-4.5,16,23], "ob")
plt.show()Aa
point + line ( temp )
import matplotlib.pyplot as plt
days = list(range(1,9))
celsius_min = [19.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
celsius_max = [24.8, 28.9, 31.3, 33.0, 34.9, 35.6, 38.4, 39.2]
fig, ax = plt.subplots()
ax.set(xlabel = "Day",
ylabel = "Temp in Area",
title = "Temp Graph"
)
ax.plot(
days, celsius_min,
days ,celsius_min, "oy",
days, celsius_max,
days, celsius_max , "or"
)
plt.show()
bar
import matplotlib.pyplot as plt
import numpy as np
years = [str(year) for year in range(2010, 2021)]
visitors = (1241, 50927, 162242, 222093,
665004, 2071987, 2460407, 3799215,
5399000, 5474016, 6003672)
plt.bar(years, visitors, color = "green")
plt.xlabel("Years")
plt.ylabel("Values")
plt.title("Bar Chart")
plt.show()
bar + point + line
import matplotlib.pyplot as plt
import numpy as np
years = [str(year) for year in range(2010, 2021)]
visitors = (1241, 50927, 162242, 222093,
665004, 2071987, 2460407, 3799215,
5399000, 5474016, 6003672)
fig, ax = plt.subplots()
ax.plot(
years, visitors,
years ,visitors, "ob",
)
plt.bar(years, visitors, color = "green")
plt.xlabel("Years")
plt.ylabel("Values")
plt.title("Bar Chart")
plt.show()
histogram
import matplotlib.pyplot as plt
import numpy as np
#정규분포
gaussian_numbers = np.random.normal(size=10000)
plt.hist(gaussian_numbers, bins = 20)
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Gaussian Histogram")
plt.show()
scatter
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 11)
y1 = np.random.randint(2, 7, (11,))
y2 = np.random.randint(9, 14, (11,))
y3 = np.random.randint(15, 25, (11,))
plt.scatter(x, y1)
plt.scatter(x, y2, marker = 'v', color = 'r')
plt.scatter(x, y3, marker = '^', color = 'y')
plt.title('Scatter Graph')
plt.show()
stack
import matplotlib.pyplot as plt
idxes = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
y1 = [23, 42, 33, 43, 8, 44, 43, 18, 21]
y2 = [9, 31, 25, 14, 17, 17, 42, 22, 28]
y3 = [18, 29, 19, 22, 18, 16, 13, 32, 21]
plt.stackplot(idxes, y1, y2, y3)
plt.title('StackPlot')
plt.show()
pie
import matplotlib.pyplot as plt
labels = 'C', 'Python', 'Java', 'C++', 'C#'
sizes = [13.38, 20.87, 11.74, 7.81, 4.41]
explode = (0, 0.1, 0, 0, 0)
fig, ax = plt.subplots()
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=0)
ax.axis('equal')
plt.title('Pie Chart')
plt.show()
매개변수
=============================================
character description
=============================================
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
===============================================
The following color abbreviations are supported:
==================
character color
==================
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
==================
import matplotlib.pyplot as plt
days = list(range(0, 22, 3))
print("Values of days:", days)
# our Y values:
celsius_values = [25.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
plt.plot(days, celsius_values, 'r--')
plt.plot(days, celsius_values, 'b|')
plt.show()
기초
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
print(fig)
print(ax)
print(type(fig))
print(type(ax))
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
X = [2, 4, 6, 8, 10]
Y = [1, 4, 9, 19, 39]
plt.plot(X,Y,'r')
plt.show()
Label on Axes
- matplotlib.pyplot.subplots
- matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None, **fig_kw)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
X = [2, 4, 6, 8, 10]
Y = [1, 4, 9, 19, 39]
plt.plot(X,Y,'r')
ax.set(
xlabel = 'Day',
ylabel = 'Temp in Area',
title = 'temp plot'
)
plt.show()
CHECKING AND DEFINING THE RANGE OF AXES
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
days = list(range(1, 9))
celsius_values = [25.6, 24.1, 26.7, 28.3, 27.5, 30.5, 32.8, 33.1]
ax.set(
xlabel = 'Day',
ylabel = 'Temp in Celcius',
title = 'temp graph',
)
ax.plot(
days, celsius_values
)
ax.axis([0, 10, 14, 45])
# xmin , xmax, ymin, ymax = 0, 10, 14, 45
# ax.axis([xmin, xmax, ymin, ymax])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-2 * np.pi, 2 * np.pi, 50, endpoint=True)
F1 = 3 * np.sin(X)
F2 = np.sin(2*X)
F3 = 0.3 * np.sin(X)
fig, ax = plt.subplots()
xmin, xmax, ymin, ymax = -2 * np.pi-0.1,2 * np.pi+0.1, -3.1, 3.1
ax.axis = ([xmin, xmax, ymin, ymax])
ax.plot(X,F1, X,F2,X,F3)
plt.show()
SHADING REGIONS WITH FILL_BETWEEN()
- matplotlib.pyplot.fill_between
- matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs)
import matplotlib.pyplot as plt
import numpy as np
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
fig, ax = plt.subplots()
ax.plot(X,Y,'b', alpha = 1)
ax.fill_between(X, y1 = 0, y2 = Y, color = 'blue', alpha = 0.3)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)
Y1 = np.sin(X)
fig, ax = plt.subplots()
ax.plot(X, Y, X, Y1, alpha = 1) #alpha = 투명도
ax.fill_between(X, y1 = Y1, y2 = Y, color = 'blue', alpha = 0.3)
plt.show()
SPINES AND TICK
matplotlib.spines
- class matplotlib.spines.Spine(axes, spine_type, path, **kwargs)
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
F1 = np.sin(2* X)
F2 = (2*X**5 + 4*X**4 - 4.8*X**3 + 1.2*X**2 + X + 1)*np.exp(-X**2)
fig, ax = plt.subplots()
ax.plot(X, F1, X, F2)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
F1 = np.sin(2* X)
F2 = (2*X**5 + 4*X**4 - 4.8*X**3 + 1.2*X**2 + X + 1)*np.exp(-X**2)
fig, ax = plt.subplots()
ax.plot(X, F1, X, F2)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
F1 = np.sin(2* X)
F2 = (2*X**5 + 4*X**4 - 4.8*X**3 + 1.2*X**2 + X + 1)*np.exp(-X**2)
fig, ax = plt.subplots()
ax.plot(X, F1, X, F2)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
plt.show()
Ticks
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
xticks = ax.get_xticks()
yticks = ax.get_yticks()
xticklabels = ax.get_xticklabels()
yticklabels = ax.get_yticklabels()
ax.set_xticks([7,13,19,33,42])
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
xticks = ax.get_xticks()
xticklabels = ax.get_xticklabels()
ax.set_xticks([7,13,19,33,42])
ax.set_xticklabels(['Korea','London','Hamburg','Toronto','Berlin'])
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
F1 = np.sin(X**2)
F2 = X * np.sin(X)
fig, ax = plt.subplots()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
ax.set_xticks([-6.28, -3.14, 3.14, 6.28])
ax.set_yticks([-3, -1, 0, +1])
ax.plot(X, F1, X, F2)
plt.show()
Setting Ticks Labels
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-2 * np.pi, 2 * np.pi, 100)
F1 = np.sin(X)
F2 = 3 * np.sin(X)
fig, ax = plt.subplots()
ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
ax.set_xticklabels([r'$-2\\pi$', r'$-\\frac{3\\pi}{2}$', r'$-\\pi$',
r'$-\\frac{\\pi}{2}$', 0, r'$\\frac{\\pi}{2}$',
r'$+\\pi$', r'$\\frac{3\\pi}{2}$', r'$+2\\pi$'])
ax.plot(X, F1, X, F2)
plt.show()
LEGENDS AND ANNOTATIONS - Legend
Location String Location Code
=============== =============
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
=============== =============
from polynomial import Polynomial
import numpy as np
import matplotlib.pyplot as plt
p = Polynomial(-0.8, 2.3, 0.5, 1, 0.2)
p_der = p.derivative
fig, ax = plt.subplots()
X = np.linspace(-2, 3, 50, endpoint=True)
F = p(X)
F_derivative = p_der(X)
ax.plot(X, F, label = 'P')
ax.plot(X, F_derivative, label = 'derivation of P')
ax.legend(loc = 'lower left')
plt.show()
from polynomial import Polynomial
import numpy as np
import matplotlib.pyplot as plt
p = Polynomial(-0.8, 2.3, 0.5, 1, 0.2)
p_der = p.derivative
fig, ax = plt.subplots()
X = np.linspace(-2, 3, 50, endpoint=True)
F = p(X)
F_derivative = p_der(X)
ax.plot(X, F, X, F_derivative)
ax.legend(['P','derivation of P'], loc = 'lower left')
plt.show()
from polynomial import Polynomial
import numpy as np
import matplotlib.pyplot as plt
p = Polynomial(2, 3, -4, 6)
p_der = p.derivative
fig, ax = plt.subplots()
X = np.linspace(-2, 3, 50, endpoint=True)
F = p(X)
F_derivative = p_der(X)
ax.plot(X, F, label = f'$ {p} $')
ax.plot(X, F_derivative, label = f'$ {p_der} $')
ax.legend(loc = 'upper left')
plt.show()
LEGENDS AND ANNOTATIONS - Annotations(주석 달기)
- matplotlib.pyplot.annotate(text, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)
plt.annotate('dd', ## 텍스트
xy=(0.1, 0.4), ## 화살이 가르킬 위치
xytext=(0.8, 0.6), ## 텍스트 위치
fontsize=40, ## font 크기
fontproperties=BMDOHYEON,
arrowprops=dict(facecolor='red', ## 내부 색깔
edgecolor='black', ## 선 색깔
fill=True, ## 내부가 비어짐(fill white와 같은 )
shrink=0.15, ## 텍스트로부터 얼마나 떨어진 위치에서 화살표가 시작하는가? 0이 최소 1이 최대
headwidth=80, ## 화살 너비
headlength=100, ## 화살 길이
width=30, ## 화살표에서 화살이 아닌 부분의 너비
linewidth=10, ## polygon의 선
linestyle=':', ## 선의 특성
alpha=0.8, ## 투명도, line, fill을 따로 지정할 수 있는지는 모르겠음.
)
)
from polynomial import Polynomial
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
X = np.arange(-5, 5, 0.1)
p = Polynomial(1, 0, -12, 0)
p_der = p.derivative
F = p(X)
F_derivative = p_der(X)
ax.plot(X, F, label = f'$ {p} $')
ax.plot(X, F_derivative, label = f'$ {p_der} $')
#1. 주석 달기(s, xy)
plt.annotate("local maximum",(-2,p(-2)))
plt.annotate("local minimum",(2,p(2)))
plt.annotate("inflection point",(0,p(0)))
ax.legend(loc = 'best')
plt.show()
from polynomial import Polynomial
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
X = np.arange(-5, 5, 0.1)
p = Polynomial(1, 0, -12, 0)
p_der = p.derivative
F = p(X)
F_derivative = p_der(X)
xpoint = [-2, 0, 2]
ypoint = [p(-2), p(0), p(2)]
ax.plot(xpoint, ypoint, 'ro')
ax.plot(X, F, label = f'$ {p} $')
ax.plot(X, F_derivative, label = f'$ {p_der} $')
# 주석 달기(s, xy)
plt.annotate("local maximum",
(-2,p(-2)),
xytext = (-2+1, p(-2)+30),
arrowprops=dict(facecolor='yellow', ## 내부 색깔
edgecolor='black', ## 선 색깔
fill=True, ## 내부가 비어짐(fill white와 같은 )
shrink=0.15, ## 텍스트로부터 얼마나 떨어진 위치에서 화살표가 시작하는가? 0이 최소 1이 최대
# headwidth=80, ## 화살 너비
# headlength=100, ## 화살 길이
# width=30, ## 화살표에서 화살이 아닌 부분의 너비
#linewidth=10, ## polygon의 선
#linestyle=':', ## 선의 특성
alpha=0.8, ## 투명도, line, fill을 따로 지정할 수 있는지는 모르겠음.
)
)
plt.annotate("local minimum",
(2,p(2)),
xytext = (2, p(2)-30),
arrowprops=dict(facecolor='yellow', ## 내부 색깔
edgecolor='black', ## 선 색깔
fill=True, ## 내부가 비어짐(fill white와 같은 )
shrink=0.15, ## 텍스트로부터 얼마나 떨어진 위치에서 화살표가 시작하는가? 0이 최소 1이 최대
# headwidth=80, ## 화살 너비
# headlength=100, ## 화살 길이
# width=30, ## 화살표에서 화살이 아닌 부분의 너비
#linewidth=10, ## polygon의 선
#linestyle=':', ## 선의 특성
alpha=0.8, ## 투명도, line, fill을 따로 지정할 수 있는지는 모르겠음.
)
)
plt.annotate("inflection point",
(0,p(0)),
xytext = (0, p(0)+30),
arrowprops=dict(facecolor='yellow', ## 내부 색깔
edgecolor='black', ## 선 색깔
fill=True, ## 내부가 비어짐(fill white와 같은 )
shrink=0.15, ## 텍스트로부터 얼마나 떨어진 위치에서 화살표가 시작하는가? 0이 최소 1이 최대
# headwidth=80, ## 화살 너비
# headlength=100, ## 화살 길이
# width=30, ## 화살표에서 화살이 아닌 부분의 너비
#linewidth=10, ## polygon의 선
#linestyle=':', ## 선의 특성
alpha=0.8, ## 투명도, line, fill을 따로 지정할 수 있는지는 모르겠음.
)
)
ax.legend(loc = 'best')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-4.1, 3.1, 150, endpoint=True)
F = X**5 + 3*X**4 - 11*X**3 - 27*X**2 + 10*X + 24
fig, ax = plt.subplots()
ax.plot(X, F)
minimum1 = -1.5264814, -7.051996717492152
minimum2 = 2.3123415793720303, -81.36889464201387
ax.annotate("minima",
xy=minimum1,
xytext=(-1.5, -50),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3,angleA=0,angleB=-90"))
ax.annotate(" ",
xy=minimum2,
xytext=(-0.7, -50),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3,angleA=0,angleB=-90"))
maximum1 = -3.35475845886632, 56.963107876630595
maximum2 = .16889828232847673, 24.868343482875485
ax.annotate("maxima", xy=maximum1,
xytext=(-1.5, 30),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3,angleA=0,angleB=-90"))
ax.annotate(" ",
xy=maximum2,
xytext=(-0.6, 30),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3,angleA=0,angleB=-90"))
zeroes = -4, -2, -1, 1, 3
for zero in zeroes:
zero = zero, 0
ax.annotate("Zeroes",
xy=zero,
color="orange",
bbox=dict(boxstyle="round", fc="none", ec="green"),
xytext=(1, 40),
arrowprops=dict(arrowstyle="->", color="orange",
connectionstyle="angle3,angleA=0,angleB=-90"))
plt.show()
'빅데이터 분석가 양성과정 > Python' 카테고리의 다른 글
Pandas (0) | 2024.07.09 |
---|---|
Matplotlib ( 2 ) (0) | 2024.07.09 |
Numpy ( 3 ) (0) | 2024.07.09 |
Numpy ( 2 ) (0) | 2024.07.09 |
Numpy ( 1 ) (0) | 2024.07.09 |