#개념 정리
#패스트캠퍼스 강의 정리
seaborn
: matplotlib을 더 사용하기 쉽게 해주는 라이브러리
seaborn 공시 도큐먼트 살펴보기
plt.rc('font', family='NanumBarunGothic')
plt.rcParams["figure.figsize"] = (12, 9)
0. seaborn이란?
- seaborn에서만 제공되는 통계 기반 plot
- 아름다운 스타일링 : matplotlib의 기본 컬러 색상보다 default 컬러가 예쁘게 조합된다.
- 컬러 팔레트 #seaborn의 컬러팔레트
- pandas 데이터프레임과 높은 호환성
1. Scatterplot
0~1 사이의 임의의 랜덤한 값을 생성한다.
1-1. x, y, colors, area 설정하기
- colors는 임의 값을 color 값으로 변환한다.
- area는 점의 넓이를 나타낸다. 값이 커지면 당연히 넓이도 커진다.
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.arange(50)
area = x * y * 1000
plt.scatter(x, y, s=area, c=colors)
plt.show()
- seaborn에서는 size와 sizes를 동시에 지정한다.
- sizes 옵션에서는 사이즈의 min, max를 명시해준다.
- hue는 컬러 옵션이다.
- palette를 통해 seaborn이 제공하는 아름다운 palette를 이용한다.
sns.scatterplot(x, y, size=area, sizes=(area.min(), area.max()), hue=area, palette='coolwarm')
plt.show()
1-2. cmap과 alpha
- cmap에 컬러를 지정하면, 컬러 값을 모두 같게 가져갈 수 있다.
- alpha값은 투명도를 나타내며, 0~1 사이의 값을 지정해 줄 수 있다. 0에 가까울수록 투명한 값을 가진다.
plt.figure(figsize=(12, 6))
plt.subplot(131)
plt.scatter(x, y, s=area, c='blue', alpha=0.1)
plt.title('alpha=0.1')
plt.subplot(132)
plt.title('alpha=0.5')
plt.scatter(x, y, s=area, c='red', alpha=0.5)
plt.subplot(133)
plt.title('alpha=1.0')
plt.scatter(x, y, s=area, c='green', alpha=1.0)
plt.show()
2. Barplot, Barhplot
2-1. 기본 Barplot 그리기
x = ['Math', 'Programming', 'Data Science', 'Art', 'English', 'Physics']
y = [66, 80, 60, 50, 80, 10]
sns.barplot(x, y, alpha=0.8, palette='YlGnBu')
plt.ylabel('Scores')
plt.title('Subjects')
plt.show()
2-2. 기본 Barhplot 그리기
x = ['Math', 'Programming', 'Data Science', 'Art', 'English', 'Physics']
y = [66, 80, 60, 50, 80, 10]
ax = sns.barplot(y, x, alpha=0.9, palette='YlOrRd')
plt.xlabel('Scores')
plt.title('Subjects')
plt.show()
3. Line Plot
3-1. 기본 lineplot 그리기
sns.set_style("darkgrid")
sns.lineplot(x, y)
plt.xlabel('x value', fontsize=15)
plt.ylabel('y value', fontsize=15)
plt.title('sin graph', fontsize=18)
plt.show()
3-2. 2개 이상 그래프 그리기
- color: 컬러 옵션
- alpha: 투명도 옵션
x = np.arange(0, 10, 0.1)
y_1 = 1 + np.sin(x)
y_2 = 1 + np.cos(x)
plt.plot(x, y_1, label='1+sin', color='blue', alpha=0.3)
plt.plot(x, y_2, label='1+cos', color='red', alpha=0.7)
plt.xlabel('x value', fontsize=15)
plt.ylabel('y value', fontsize=15)
plt.title('sin and cos graph', fontsize=18)
plt.grid()
plt.legend()
plt.show()
3-3. 마커 스타일링
x = np.arange(0, 10, 0.1)
y_1 = 1 + np.sin(x)
y_2 = 1 + np.cos(x)
plt.plot(x, y_1, label='1+sin', color='blue', alpha=0.3, marker='o')
plt.plot(x, y_2, label='1+cos', color='red', alpha=0.7, marker='+')
plt.xlabel('x value', fontsize=15)
plt.ylabel('y value', fontsize=15)
plt.title('sin and cos graph', fontsize=18)
plt.grid()
plt.legend()
plt.show()
3-4. 라인 스타일 변경하기
x = np.arange(0, 10, 0.1)
y_1 = 1 + np.sin(x)
y_2 = 1 + np.cos(x)
plt.plot(x, y_1, label='1+sin', color='blue', linestyle=':')
plt.plot(x, y_2, label='1+cos', color='red', linestyle='-.')
plt.xlabel('x value', fontsize=15)
plt.ylabel('y value', fontsize=15)
plt.title('sin and cos graph', fontsize=18)
plt.grid()
plt.legend()
plt.show()
4. Areaplot(Filled Area)
fill_between 함수 사용
4-1. 기본 areaplot 그리기
x = np.arange(1,21)
y = np.random.randint(low=5, high=10, size=20)
# fill_between으로 색칠하기
plt.fill_between(x, y, color="green", alpha=0.6)
plt.show()
4-2. 경계선을 굵게, area는 옅게 그리기
plt.fill_between( x, y, color="green", alpha=0.3)
plt.plot(x, y, color="green", alpha=0.8)
4-3. 여러 그래프 겹쳐 그리기
x = np.arange(1, 10, 0.05)
y_1 = np.cos(x)+1
y_2 = np.sin(x)+1
y_3 = y_1 * y_2 / np.pi
plt.fill_between(x, y_1, color="green", alpha=0.1)
plt.fill_between(x, y_2, color="blue", alpha=0.2)
plt.fill_between(x, y_3, color="red", alpha=0.3)
5. Histogram
5-1. 기본 Histogram 그리기
sns.distplot(x, bins=bins, kde=False, hist=True, color='g')
kde를 True로 설정하면, Density가 Y축에 표기된다.
sns.distplot(x, bins=bins, kde=True, hist=True, vertical=True, color='r')
- sharey: y축을 다중 그래프가 share
- tight_layout: graph의 패딩을 자동으로 조절해주어 fit한 graph를 생성
5-2. 다중 Histogram 그리기
N = 100000
bins = 30
x = np.random.randn(N)
fig, axs = plt.subplots(1, 3,
sharey=True,
tight_layout=True
)
fig.set_size_inches(12, 5)
axs[0].hist(x, bins=bins)
axs[1].hist(x, bins=bins*2)
axs[2].hist(x, bins=bins*4)
plt.show()
6. Pie Chart
pie chart 옵션
- explode: 파이에서 툭 튀어져 나온 비율
- autopct: 퍼센트 자동으로 표기
- shadow: 그림자 표시
- startangle: 파이를 그리기 시작할 각도
texts: label에 대한 텍스트 효과
autotexts: 파이 위에 그려지는 텍스트 효과
labels = ['Samsung', 'Huawei', 'Apple', 'Xiaomi', 'Oppo', 'Etc']
sizes = [20.4, 15.8, 10.5, 9, 7.6, 36.7]
explode = (0.3, 0, 0, 0, 0, 0)
# texts, autotexts 인자를 활용하여 텍스트 스타일링을 적용합니다
patches, texts, autotexts = plt.pie(sizes,
explode=explode,
labels=labels,
autopct='%1.1f%%',
shadow=True,
startangle=90)
plt.title('Smartphone pie', fontsize=15)
# label 텍스트에 대한 스타일 적용
for t in texts:
t.set_fontsize(12)
t.set_color('gray')
# pie 위의 텍스트에 대한 스타일 적용
for t in autotexts:
t.set_color("white")
t.set_fontsize(18)
plt.show()
7. Box plot
7-1. 기본 박스플롯 생성
sns.boxplot(data, orient='v', width=0.2)
plt.show()
7-2. Outlier 마커 심볼과 컬러 변경
outlier_marker = dict(markerfacecolor='r', marker='D')
plt.title('Changed Outlier Symbols', fontsize=15)
plt.boxplot(data, flierprops=outlier_marker)
plt.show()
8. 3D 그래프 그리기
from mpl_toolkits import mplot3d
8-1. 밑그림 그리기 (캔버스)
fig = plt.figure()
ax = plt.axes(projection='3d')
8-2. 3d plot 그리기
ax = plt.axes(projection='3d')
# x, y, z 데이터를 생성합니다
z = np.linspace(0, 15, 1000)
x = np.sin(z)
y = np.cos(z)
ax.plot(x, y, z, 'gray')
plt.show()
8-3. 3d scatter 그리기
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111, projection='3d') # Axe3D object
sample_size = 500
x = np.cumsum(np.random.normal(0, 5, sample_size))
y = np.cumsum(np.random.normal(0, 5, sample_size))
z = np.cumsum(np.random.normal(0, 5, sample_size))
ax.scatter(x, y, z, c = z, s=20, alpha=0.5, cmap='Greens')
plt.title("ax.scatter")
plt.show()
8-4. contour3D 그리기 (등고선)
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
fig = plt.figure(figsize=(12, 6))
ax = plt.axes(projection='3d')
ax.contour3D(x, y, z, 20, cmap=plt.cm.rainbow)
plt.title("ax.contour3D")
plt.show()
9. imshow
이미지 데이터와 유사하게 행과 열을 가진 2차원의 데이터를 시각화할 때 사용
from sklearn.datasets import load_digits
digits = load_digits()
X = digits.images[:10]
X[0]
- load_digits는 0~16 값을 가지는 array로 이루어져 있다.
- 1개의 array는 8 X 8 배열 안에 표현되어 있다.
- 숫자는 0~9까지 이루어져있다.
fig, axes = plt.subplots(nrows=2, ncols=5, sharex=True, figsize=(12, 6), sharey=True)
for i in range(10):
axes[i//5][i%5].imshow(X[i], cmap='Blues')
axes[i//5][i%5].set_title(str(i), fontsize=20)
plt.tight_layout()
plt.show()