Repository navigation
Expand file tree
/
Copy pathsubplotEx.py
More file actions
85 lines (69 loc) · 3.21 KB
/
Copy pathsubplotEx.py
File metadata and controls
85 lines (69 loc) · 3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# 한 그림에 여러 그래프 배치
import matplotlib.pyplot as plt
import numpy as np
import krfont
krfont.apply(verbose=False)
SHOW = False
rng = np.random.default_rng(7)
월 = np.arange(1, 13)
매출 = np.array([355, 201, 268, 302, 142, 327, 257, 221, 187, 240, 250, 247])
print('========== 2x2 배치 ==========')
fig, axes = plt.subplots(2, 2, figsize=(10, 7))
# axes 는 2x2 넘파이 배열입니다. step10 의 인덱싱이 그대로 쓰입니다.
print('axes 의 타입 :', type(axes).__name__, '| shape :', axes.shape)
axes[0, 0].plot(월, 매출, marker='o')
axes[0, 0].set_title('선 그래프')
axes[0, 1].bar(['음료', '베이커리', '디저트'], [1484, 762, 756])
axes[0, 1].set_title('막대 그래프')
axes[1, 0].hist(rng.normal(70, 12, 300), bins=20, edgecolor='white')
axes[1, 0].set_title('히스토그램')
axes[1, 1].scatter(rng.integers(1, 13, 100), rng.integers(100, 800, 100), alpha=0.5)
axes[1, 1].set_title('산점도')
fig.suptitle('2019년 매출 요약', fontsize=15) # 전체 제목
fig.tight_layout() # 겹침 자동 정리
fig.savefig('output/40_grid.png', dpi=100, bbox_inches='tight')
plt.close(fig)
print('40_grid.png')
print('※ tight_layout() 을 빼면 제목과 축 이름이 서로 겹칩니다. 거의 항상 부르세요.')
print('\n========== 1행 배치와 축 공유 ==========')
fig, axes = plt.subplots(1, 3, figsize=(12, 3.5), sharey=True)
for ax, (name, data) in zip(axes, [
('서울', 매출), ('부산', 매출 * 0.7), ('대구', 매출 * 0.5)]):
ax.plot(월, data, marker='o')
ax.set_title(name)
ax.set_xlabel('월')
axes[0].set_ylabel('매출 (천원)')
fig.tight_layout()
fig.savefig('output/41_sharey.png', dpi=100, bbox_inches='tight')
plt.close(fig)
print('41_sharey.png')
print('※ sharey=True 로 y축을 맞춰야 세 그래프를 정직하게 비교할 수 있습니다.')
print(' 축이 제각각이면 작은 값이 큰 값처럼 보입니다.')
print('\n========== 반복문으로 그리기 ==========')
지역들 = {'서울': 1.0, '경기': 0.9, '부산': 0.75, '대구': 0.6, '광주': 0.65, '대전': 0.55}
fig, axes = plt.subplots(2, 3, figsize=(12, 6), sharex=True, sharey=True)
for ax, (name, ratio) in zip(axes.flat, 지역들.items()):
# axes.flat 으로 2차원을 1차원처럼 순회 (step10 의 flatten 과 같은 개념)
ax.bar(월, 매출 * ratio, color='#4C72B0')
ax.set_title(name, fontsize=10)
fig.suptitle('지역별 월 매출', fontsize=14)
fig.supxlabel('월')
fig.supylabel('매출 (천원)')
fig.tight_layout()
fig.savefig('output/42_loop.png', dpi=100, bbox_inches='tight')
plt.close(fig)
print('42_loop.png')
print('\n========== 크기가 다른 배치 ==========')
fig = plt.figure(figsize=(10, 5))
gs = fig.add_gridspec(2, 3)
ax_big = fig.add_subplot(gs[:, :2]) # 왼쪽 2칸을 세로로 합쳐 크게
ax_big.plot(월, 매출, marker='o')
ax_big.set_title('주 그래프')
fig.add_subplot(gs[0, 2]).bar(['A', 'B'], [3, 5])
fig.add_subplot(gs[1, 2]).pie([3, 5], labels=['A', 'B'])
fig.tight_layout()
fig.savefig('output/43_gridspec.png', dpi=100, bbox_inches='tight')
plt.close(fig)
print('43_gridspec.png — 중요한 그래프를 크게, 보조를 작게 배치할 때')
if SHOW:
plt.show()