Repository navigation
Expand file tree
/
Copy pathstyleEx.py
More file actions
103 lines (89 loc) · 4.47 KB
/
Copy pathstyleEx.py
File metadata and controls
103 lines (89 loc) · 4.47 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# 보기 좋게 다듬기 — 색·범례·축·주석
import matplotlib.pyplot as plt
import numpy as np
import krfont
krfont.apply(verbose=False)
SHOW = False
월 = np.arange(1, 13)
매출 = np.array([355, 201, 268, 302, 142, 327, 257, 221, 187, 240, 250, 247])
print('========== 색 지정 4가지 ==========')
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.plot(월, 매출 + 0, color='crimson', label="이름 'crimson'")
ax.plot(월, 매출 + 40, color='#4C72B0', label="16진수 '#4C72B0'")
ax.plot(월, 매출 + 80, color=(0.3, 0.7, 0.4), label='RGB 튜플 (0~1)')
ax.plot(월, 매출 + 120, color='C3', label="기본 팔레트 'C3'")
ax.legend(fontsize=8)
ax.set_title('색 지정 방법')
fig.savefig('output/30_colors.png', dpi=100, bbox_inches='tight')
plt.close(fig)
print('30_colors.png')
print('\n========== 선 스타일과 표식 ==========')
fig, ax = plt.subplots(figsize=(7, 3.5))
for i, (ls, marker) in enumerate([('-', 'o'), ('--', 's'), (':', '^'), ('-.', 'D')]):
ax.plot(월, 매출 + i * 40, linestyle=ls, marker=marker,
label=f"linestyle='{ls}' marker='{marker}'")
ax.legend(fontsize=8)
ax.set_title('선 스타일과 표식')
fig.savefig('output/31_styles.png', dpi=100, bbox_inches='tight')
plt.close(fig)
print('31_styles.png')
print('\n========== 축 다듬기 ==========')
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(월, 매출, marker='o', color='#4C72B0')
ax.set_title('2019년 월별 매출', fontsize=14, pad=12)
ax.set_xlabel('월')
ax.set_ylabel('매출 (천원)')
ax.set_xticks(월) # 눈금을 12개 전부
ax.set_xticklabels([f'{m}월' for m in 월])
ax.set_ylim(0, 400) # y축을 0부터 (중요!)
ax.grid(axis='y', alpha=0.3) # 가로 격자만
ax.spines['top'].set_visible(False) # 위·오른쪽 테두리 제거
ax.spines['right'].set_visible(False)
fig.savefig('output/32_axes.png', dpi=100, bbox_inches='tight')
plt.close(fig)
print('32_axes.png')
print('''
⚠️ y축을 0부터 시작하지 않으면 차이가 과장됩니다.
막대 그래프에서는 특히 그렇습니다. 100 과 105 를 y축 99~106 으로 그리면
5배 차이처럼 보입니다. 막대는 반드시 0부터 시작하세요.
(선 그래프는 변화를 보는 것이라 0부터가 아니어도 되는 경우가 있습니다)
''')
print('========== 강조하기 : 주석과 보조선 ==========')
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(월, 매출, marker='o', color='lightgray', zorder=1)
최고 = 매출.argmax()
최저 = 매출.argmin()
ax.scatter([월[최고], 월[최저]], [매출[최고], 매출[최저]],
color=['crimson', 'steelblue'], s=90, zorder=3)
ax.annotate(f'최고 {매출[최고]}',
xy=(월[최고], 매출[최고]), xytext=(월[최고] + 1, 매출[최고] + 20),
arrowprops=dict(arrowstyle='->', color='crimson'), color='crimson')
ax.annotate(f'최저 {매출[최저]}',
xy=(월[최저], 매출[최저]), xytext=(월[최저] + 1, 매출[최저] - 40),
arrowprops=dict(arrowstyle='->', color='steelblue'), color='steelblue')
ax.axhline(매출.mean(), color='gray', linestyle='--', alpha=0.6)
ax.text(0.6, 매출.mean() + 8, f'평균 {매출.mean():.0f}', color='gray', fontsize=9)
ax.set_title('강조가 있는 그래프')
ax.set_ylim(0, 420)
ax.grid(axis='y', alpha=0.2)
fig.savefig('output/33_annotate.png', dpi=100, bbox_inches='tight')
plt.close(fig)
print('33_annotate.png — 보여 주고 싶은 것만 색을 주고 나머지는 회색으로.')
print(' 전부 알록달록하면 아무것도 강조되지 않습니다.')
print('\n========== 스타일 시트 ==========')
print('사용 가능한 스타일 :', plt.style.available[:6], '...')
for style in ['default', 'ggplot', 'seaborn-v0_8-whitegrid']:
if style != 'default' and style not in plt.style.available:
continue
with plt.style.context(style): # with 안에서만 적용된다
krfont.apply(verbose=False) # 스타일이 폰트를 되돌리므로 다시 적용
fig, ax = plt.subplots(figsize=(5, 3))
ax.plot(월, 매출, marker='o')
ax.set_title(f'스타일 : {style}')
fig.savefig(f'output/34_style_{style.replace("-", "_")}.png',
dpi=100, bbox_inches='tight')
plt.close(fig)
print('34_style_*.png 저장')
print('※ 스타일을 적용하면 폰트 설정이 초기화됩니다. krfont.apply() 를 다시 부르세요.')
if SHOW:
plt.show()