콘텐츠로 이동

hossam.my_plot

hossam.my_plot

init

init(
    width=1280,
    height=640,
    rows=1,
    cols=1,
    title=None,
    xlabel=None,
    ylabel=None,
    grid=True,
    twinx=False,
)

그래프의 크기와 dpi를 설정하여 fig와 ax 객체를 반환하는 함수

Parameters:

Name Type Description Default
- width

그래프의 가로 크기 (픽셀 단위)

required
- height

그래프의 세로 크기 (픽셀 단위)

required
- rows

그래프의 행 수

required
- cols

그래프의 열 수

required
- title

그래프의 제목 (기본값: None)

required
- xlabel

x축 레이블 (기본값: None)

required
- ylabel

y축 레이블 (기본값: None)

required
- grid

그래프에 그리드를 표시할지 여부 (기본값: True)

required
- twinx

y축이 2개인 그래프를 그릴 때, 두 번째 y축을 생성할지 여부 (기본값: False)

required

Returns:

Type Description
  • fig: 생성된 Figure 객체
  • ax: 생성된 Axes 객체 또는 Axes 배열
Source code in hossam/my_plot.py
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
def init(width=1280, height=640, rows=1, cols=1, title=None, xlabel=None, ylabel=None, grid=True, twinx=False):
    """
    그래프의 크기와 dpi를 설정하여 fig와 ax 객체를 반환하는 함수

    Parameters:
        - width: 그래프의 가로 크기 (픽셀 단위)
        - height: 그래프의 세로 크기 (픽셀 단위)
        - rows: 그래프의 행 수
        - cols: 그래프의 열 수
        - title: 그래프의 제목 (기본값: None)
        - xlabel: x축 레이블 (기본값: None)
        - ylabel: y축 레이블 (기본값: None)
        - grid: 그래프에 그리드를 표시할지 여부 (기본값: True)
        - twinx: y축이 2개인 그래프를 그릴 때, 두 번째 y축을 생성할지 여부 (기본값: False)

    Returns:
        - fig: 생성된 Figure 객체
        - ax: 생성된 Axes 객체 또는 Axes 배열
    """
    my_figsize = ((width / 100) * cols, (height / 100) * rows)
    fig, ax = plt.subplots(rows, cols, figsize=my_figsize, dpi=200)

    if rows > 1 or cols > 1:
        ax = ax.flatten()  # 2차원 배열을 1차원으로 평탄화하여 반복 처리
        fig.suptitle(title, fontsize=32, fontweight=500)
        for a in ax:
            a.grid(grid, alpha=0.5)

    else:
        ax.grid(grid, alpha=0.5)

        if title:
            ax.set_title(title, fontsize=24, fontweight=500, pad=15)

        if xlabel:
            ax.set_xlabel(xlabel, fontsize=16, fontweight=400, labelpad=5)

        if ylabel:
            ax.set_ylabel(ylabel, fontsize=16, fontweight=400, labelpad=5)

    if twinx:
        ax_right = ax.twinx()
        ax = (ax, ax_right)

    return fig, ax

show

show(save_path=None)

그래프를 화면에 표시하는 함수

Parameters:

Name Type Description Default
- grid

그리드를 표시할지 여부 (기본값: True)

required
- save_path

그래프를 저장할 파일 경로. None이면 저장하지 않음.

required
Source code in hossam/my_plot.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def show(save_path=None):
    """
    그래프를 화면에 표시하는 함수

    Parameters:
        - grid: 그리드를 표시할지 여부 (기본값: True)
        - save_path: 그래프를 저장할 파일 경로. None이면 저장하지 않음.
    """
    if save_path:
        plt.savefig(save_path)

    plt.tight_layout()
    plt.show()
    plt.close()

pointplot

pointplot(
    data=None,
    x=None,
    y=None,
    hue=None,
    order=None,
    hue_order=None,
    estimator="mean",
    errorbar="se",
    capsize=0.1,
    dodge=False,
    markers="o",
    linestyles="-",
    palette=None,
    color=None,
    title=None,
    xlabel=None,
    ylabel=None,
    legend_title=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

점 그래프(pointplot)를 그린다. 범주별 추정치(기본: 평균)와 오차범위를 점과 선으로 표현하므로 분산분석의 상호작용 플롯(interaction plot) 등에 활용한다.

Parameters:

Name Type Description Default
data

시각화할 데이터.

None
x

x축 범주 컬럼명.

None
y

y축 값 컬럼명.

None
hue

범주 구분 컬럼명.

None
order

x축 범주의 표시 순서.

None
hue_order

hue 범주의 표시 순서.

None
estimator

각 범주의 대표값 추정 방법 (기본 'mean').

'mean'
errorbar

오차범위 표현 방식 (예: 'se', 'sd', ('ci', 95)).

'se'
capsize

오차범위 막대 끝 모자의 크기.

0.1
dodge

hue별 점이 겹치지 않도록 좌우로 분리할지 여부 또는 분리 폭.

False
markers

점 마커 모양.

'o'
linestyles

선 스타일.

'-'
palette

색상 팔레트 이름.

None
color

단일 색상 (hue가 없을 때 사용).

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
legend_title

범례 제목 (hue가 있을 때 표시).

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def pointplot(data=None, x=None, y=None, hue=None, order=None, hue_order=None,
              estimator="mean", errorbar="se", capsize=0.1, dodge=False,
              markers="o", linestyles="-", palette=None, color=None,
              title=None, xlabel=None, ylabel=None, legend_title=None,
              width=1280, height=640, save_path=None, ax=None):
    """
    점 그래프(pointplot)를 그린다. 범주별 추정치(기본: 평균)와 오차범위를 점과 선으로 표현하므로
    분산분석의 상호작용 플롯(interaction plot) 등에 활용한다.

    Args:
        data: 시각화할 데이터.
        x: x축 범주 컬럼명.
        y: y축 값 컬럼명.
        hue: 범주 구분 컬럼명.
        order: x축 범주의 표시 순서.
        hue_order: hue 범주의 표시 순서.
        estimator: 각 범주의 대표값 추정 방법 (기본 'mean').
        errorbar: 오차범위 표현 방식 (예: 'se', 'sd', ('ci', 95)).
        capsize: 오차범위 막대 끝 모자의 크기.
        dodge: hue별 점이 겹치지 않도록 좌우로 분리할지 여부 또는 분리 폭.
        markers: 점 마커 모양.
        linestyles: 선 스타일.
        palette: 색상 팔레트 이름.
        color: 단일 색상 (hue가 없을 때 사용).
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        legend_title: 범례 제목 (hue가 있을 때 표시).
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """
    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # 점 그래프 그리기
    sb.pointplot(data=data, x=x, y=y, hue=hue, order=order, hue_order=hue_order,
                 estimator=estimator, errorbar=errorbar, capsize=capsize, dodge=dodge,
                 markers=markers, linestyles=linestyles, palette=palette, color=color, ax=ax)

    # 범례 제목 설정 (hue가 있을 때)
    if hue is not None and legend_title is not None:
        legend = ax.get_legend()
        if legend is not None:
            legend.set_title(legend_title)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

kdeplot

kdeplot(
    data=None,
    x=None,
    hue=None,
    meanline=False,
    clevel=0,
    title=None,
    xlabel=None,
    ylabel=None,
    fill=False,
    linewidth=2.0,
    palette=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

단변량 커널 밀도 그래프를 그린다. hue가 지정된 경우 범주별 평균선을 함께 표시한다.

Parameters:

Name Type Description Default
data

시각화할 데이터.

None
x

x축 컬럼명 혹은 x축 값 시퀀스.

None
hue

범주 구분 컬럼명.

None
meanline

평균선 표시 여부.

False
clevel

모평균 신뢰구간을 표시할 신뢰수준. 0이면 표시하지 않는다 (기본값: 0).

0
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
fill

면적 채우기 여부.

False
linewidth

선 굵기.

2.0
palette

색상 팔레트 이름.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def kdeplot(data=None, x=None, hue=None, meanline=False, clevel=0,
            title=None, xlabel=None, ylabel=None, fill=False, linewidth=2.0, palette=None,
            width=1280, height=640, save_path=None, ax=None):
    """
    단변량 커널 밀도 그래프를 그린다. hue가 지정된 경우 범주별 평균선을 함께 표시한다.

    Args:
        data: 시각화할 데이터.
        x: x축 컬럼명 혹은 x축 값 시퀀스.
        hue: 범주 구분 컬럼명.
        meanline: 평균선 표시 여부.
        clevel: 모평균 신뢰구간을 표시할 신뢰수준. 0이면 표시하지 않는다 (기본값: 0).
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        fill: 면적 채우기 여부.
        linewidth: 선 굵기.
        palette: 색상 팔레트 이름.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """

    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # 단변량 커널 밀도 그래프 그리기
    sb.kdeplot(data=data, x=x, fill=fill, hue=hue, linewidth=linewidth, palette=palette, ax=ax)

    # 신뢰구간 표시 (신뢰수준이 0이 아닌 경우에만)
    if clevel:
        ymin, ymax = ax.get_ylim()  # 그래프의 y축 범위 조회

        if hue is None:
            # 그래프에 적용된 팔레트의 첫 번째 색상을 따른다 (팔레트가 없으면 기본 파란색)
            color = sb.color_palette(palette)[0] if palette else '#0066ff'
            # 전체 데이터에 대한 신뢰구간 표시
            _draw_ci(ax, my_stats.ci(data, column=x, clevel=clevel), color, ymax)
        else:
            # hue 범주별로 신뢰구간 표시 (kdeplot이 그린 라인의 색상과 일치시킴)
            categories = list(data[hue].unique())
            # 팔레트에서 범주의 수에 맞는 색상값 추출
            colors = sb.color_palette(palette, n_colors=len(categories))

            # 각 범주에 대해 신뢰구간 표시
            for i, cat in enumerate(categories):
                cdata = data.loc[data[hue] == cat, x]
                _draw_ci(ax, my_stats.ci(cdata, clevel=clevel), colors[i], ymax)

        ax.set_ylim(ymin, ymax)  # y축 범위 유지

    # 평균선 표시
    if meanline:
        y_max = ax.get_ylim()[1]

        if hue is None:
            mv = data[x].mean()
            ax.axvline(x=mv, color='red', linestyle='--', linewidth=linewidth * 0.5)
            ax.text(x=mv + 0.05, y=y_max * 0.95, s=f'Mean: {mv:.2f}', color='red', fontsize=14, fontweight=500, ha='center')
        else:
            # hue 범주별 평균선 표시 (kdeplot이 그린 라인의 색상과 일치시킴)
            categories = list(data[hue].unique())

            # 팔레트에서 범주의 수에 맞는 색상값 추출
            colors = sb.color_palette(palette, n_colors=len(categories))

            # 각 범주에 대해 평균선 표시
            for i, cat in enumerate(categories):
                mv = data.loc[data[hue] == cat, x].mean()
                ax.axvline(x=mv, color=colors[i], linestyle='--', linewidth=linewidth * 0.5)
                ax.text(x=mv + 0.05, y=y_max * (0.95 - i * 0.07), s=f'{cat} Mean: {mv:.2f}', color=colors[i], fontsize=14, fontweight=500, ha='center')

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

histplot

histplot(
    data=None,
    x=None,
    bins="auto",
    hue=None,
    title=None,
    xlabel=None,
    ylabel=None,
    linewidth=1,
    palette=None,
    kde=False,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

히스토그램을 그린다.

Parameters:

Name Type Description Default
data

시각화할 데이터.

None
x

히스토그램 대상 컬럼명.

None
bins

구간 수 또는 경계.

'auto'
hue

범주 컬럼명.

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
linewidth

선 굵기.

1
palette

색상 팔레트 이름.

None
kde

커널 밀도 그래프 겹쳐 그릴지 여부.

False
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def histplot(data=None, x=None, bins="auto", hue=None, title=None, xlabel=None, ylabel=None, 
            linewidth=1, palette=None, kde=False, width=1280, height=640, save_path=None, ax=None):
    """
    히스토그램을 그린다.

    Args:
        data: 시각화할 데이터.
        x: 히스토그램 대상 컬럼명.
        bins: 구간 수 또는 경계.
        hue: 범주 컬럼명.
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        linewidth: 선 굵기.
        palette: 색상 팔레트 이름.
        kde: 커널 밀도 그래프 겹쳐 그릴지 여부.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """

    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # 구간 산정
    if isinstance(bins, int):
        hist, bins = np.histogram(data[x], bins=bins)
        bins = np.round(bins, 1)
        ax.set_xticks(bins, bins)
    elif isinstance(bins, (list, np.ndarray)):
        ax.set_xticks(bins, bins)

    # 히스토그램 그리기
    sb.histplot(data=data, x=x, hue=hue, linewidth=linewidth, palette=palette, kde=kde, bins=bins, ax=ax)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

boxplot

boxplot(
    data=None,
    x=None,
    y=None,
    hue=None,
    orient=None,
    palette=None,
    order=None,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

상자그림(boxplot)을 그린다.

Parameters:

Name Type Description Default
data

시각화할 데이터.

None
x

x축 범주 컬럼명.

None
y

y축 값 컬럼명.

None
hue

범주 구분 컬럼명.

None
orient

상자그림 방향 (None, 'v' 또는 'h').

None
palette

색상 팔레트 이름.

None
order

상자그림 순서를 의미하는 연속형 자료형.

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def boxplot(data=None, x=None, y=None, hue=None, orient=None, palette=None, order=None,
            title=None, xlabel=None, ylabel=None,
            width=1280, height=640, save_path=None, ax=None):
    """
    상자그림(boxplot)을 그린다.

    Args:
        data: 시각화할 데이터.
        x: x축 범주 컬럼명.
        y: y축 값 컬럼명.
        hue: 범주 구분 컬럼명.
        orient: 상자그림 방향 (None, 'v' 또는 'h').
        palette: 색상 팔레트 이름.
        order: 상자그림 순서를 의미하는 연속형 자료형.
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """
    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # 범주축(세로형이면 x, 가로형이면 y)을 기준으로 hue 처리를 결정한다.
    #  - hue 없이 palette만 지정: 범주축을 hue로 삼아 범주별 색상을 적용
    #  - hue가 범주축과 동일(중복): 외부에서 hue=x 로 호출된 경우
    # 두 경우 모두 hue가 범주축과 같으므로, 상자가 쪼개지지(dodge) 않게 끄고 범례도 숨긴다.
    cat_axis = x if orient != "h" else y
    dodge = "auto"
    legend = "auto"
    if hue is None and palette is not None:
        hue = cat_axis
        dodge = False
        legend = False
    elif hue is not None and hue == cat_axis:
        dodge = False
        legend = False

    # 상자그림 그리기
    sb.boxplot(data=data, x=x, y=y, hue=hue, orient=orient, palette=palette,
               order=order, dodge=dodge, legend=legend, ax=ax)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

violinplot

violinplot(
    data=None,
    x=None,
    y=None,
    hue=None,
    orient=None,
    palette=None,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

바이올린 플롯을 그린다.

Parameters:

Name Type Description Default
data

시각화할 데이터.

None
x

x축 범주 컬럼명.

None
y

y축 값 컬럼명.

None
hue

범주 구분 컬럼명.

None
orient

바이올린 플롯 방향 (None, 'v' 또는 'h').

None
palette

색상 팔레트 이름.

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def violinplot(data=None, x=None, y=None, hue=None, orient=None,      
               palette=None, title=None, xlabel=None, ylabel=None,
               width=1280, height=640, save_path=None, ax=None):
    """
    바이올린 플롯을 그린다.

    Args:
        data: 시각화할 데이터.
        x: x축 범주 컬럼명.
        y: y축 값 컬럼명.
        hue: 범주 구분 컬럼명.
        orient: 바이올린 플롯 방향 (None, 'v' 또는 'h').
        palette: 색상 팔레트 이름.
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """
    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # hue가 범주축(세로형=x, 가로형=y)과 같아지는 경우(palette만 지정 / 외부에서 hue=x 전달)
    # 분포가 쪼개지지(dodge) 않도록 끄고 범례도 숨긴다.
    cat_axis = x if orient != "h" else y
    dodge = "auto"
    legend = "auto"
    if hue is None and palette is not None:
        hue = cat_axis
        dodge = False
        legend = False
    elif hue is not None and hue == cat_axis:
        dodge = False
        legend = False

    # 바이올린 플롯 그리기
    sb.violinplot(data=data, x=x, y=y, hue=hue, orient=orient, palette=palette,
                  dodge=dodge, legend=legend, ax=ax)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

heatmap

heatmap(
    data=None,
    annot=True,
    fmt="0.2f",
    linewidths=0.5,
    palette=None,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

히트맵을 그린다.

Parameters:

Name Type Description Default
data

시각화할 데이터 (2차원 배열 또는 DataFrame).

None
annot

셀에 값 표시 여부.

True
fmt

셀에 표시할 값의 형식.

'0.2f'
linewidths

셀 간격 선 두께.

0.5
palette

색상 팔레트 이름.

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def heatmap(data=None, annot=True, fmt="0.2f", linewidths=0.5,
            palette=None, title=None, xlabel=None, ylabel=None,
            width=1280, height=640, save_path=None, ax=None):
    """
    히트맵을 그린다.

    Args:
        data: 시각화할 데이터 (2차원 배열 또는 DataFrame).
        annot: 셀에 값 표시 여부.
        fmt: 셀에 표시할 값의 형식.
        linewidths: 셀 간격 선 두께.
        palette: 색상 팔레트 이름.
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """

    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # 그리드 제거
    ax.grid(False)

    # 히트맵 그리기
    sb.heatmap(data=data, annot=annot, fmt=fmt, linewidths=linewidths, cmap=palette, ax=ax)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

barplot

barplot(
    data=None,
    x=None,
    y=None,
    hue=None,
    estimator=np.mean,
    order=None,
    palette=None,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

막대그래프를 그린다

Parameters:

Name Type Description Default
data

시각화할 데이터 (2차원 배열 또는 DataFrame).

None
x

x축 범주 컬럼명.

None
y

y축 값 컬럼명.

None
hue

범주 구분 컬럼명.

None
estimator

막대 높이 계산 함수 (기본값: np.mean).

mean
order

정렬 순서를 의미하는 연속형 자료형.

None
palette

색상 팔레트 이름.

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
def barplot(data=None, x=None, y=None, hue=None, estimator=np.mean,
            order=None, palette=None, title=None, xlabel=None, ylabel=None,
            width=1280, height=640, save_path=None, ax=None):
    """
    막대그래프를 그린다

    Args:
        data: 시각화할 데이터 (2차원 배열 또는 DataFrame).
        x: x축 범주 컬럼명.
        y: y축 값 컬럼명.
        hue: 범주 구분 컬럼명.
        estimator: 막대 높이 계산 함수 (기본값: np.mean).
        order: 정렬 순서를 의미하는 연속형 자료형.
        palette: 색상 팔레트 이름.
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """

    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # hue가 범주축(x, 없으면 y)과 같아지는 경우(palette만 지정 / 외부에서 hue=x 전달)
    # 막대가 쪼개지지(dodge) 않도록 끄고 범례도 숨긴다.
    cat_axis = x if x is not None else y
    dodge = "auto"
    legend = "auto"
    if hue is None and palette is not None:
        hue = cat_axis
        dodge = False
        legend = False
    elif hue is not None and hue == cat_axis:
        dodge = False
        legend = False

    # 막대그래프 그리기
    sb.barplot(data=data, x=x, y=y, hue=hue, estimator=estimator, order=order,
               palette=palette, dodge=dodge, legend=legend, ax=ax)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

countplot

countplot(
    data=None,
    x=None,
    y=None,
    hue=None,
    order=None,
    palette=None,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

빈도 그래프를 그린다

Parameters:

Name Type Description Default
data

시각화할 데이터 (2차원 배열 또는 DataFrame).

None
x

x축 범주 컬럼명.

None
y

y축 값 컬럼명.

None
hue

범주 구분 컬럼명.

None
order

정렬 순서를 의미하는 연속형 자료형.

None
palette

색상 팔레트 이름.

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
def countplot(data=None, x=None, y=None, hue=None, order=None,
            palette=None, title=None, xlabel=None, ylabel=None,
            width=1280, height=640, save_path=None, ax=None):
    """
    빈도 그래프를 그린다

    Args:
        data: 시각화할 데이터 (2차원 배열 또는 DataFrame).
        x: x축 범주 컬럼명.
        y: y축 값 컬럼명.
        hue: 범주 구분 컬럼명.
        order: 정렬 순서를 의미하는 연속형 자료형.
        palette: 색상 팔레트 이름.
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """

    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # hue가 범주축(x, 없으면 y)과 같아지는 경우(palette만 지정 / 외부에서 hue=x 전달)
    # 막대가 쪼개지지(dodge) 않도록 끄고 범례도 숨긴다.
    cat_axis = x if x is not None else y
    dodge = "auto"
    legend = "auto"
    if hue is None and palette is not None:
        hue = cat_axis
        dodge = False
        legend = False
    elif hue is not None and hue == cat_axis:
        dodge = False
        legend = False

    # 빈도 그래프 그리기
    sb.countplot(data=data, x=x, y=y, hue=hue, order=order, palette=palette,
                 dodge=dodge, legend=legend, ax=ax)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

pieplot

pieplot(
    x,
    labels,
    autopct="%0.1f%%",
    startangle=90,
    counterclock=False,
    explode=None,
    donutchart=False,
    wedge_width=0.7,
    wedge_color="#ffffff",
    wedge_linewidth=3,
    palette=None,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

파이 그래프 혹은 도넛 그래프를 그린다

Parameters:

Name Type Description Default
x

x축 범주 컬럼명.

required
labels

파이 조각에 대한 라벨.

required
autopct

퍼센트 표시 형식.

'%0.1f%%'
startangle

시작 각도.

90
counterclock

시계 반대 방향으로 그릴지 여부.

False
explode

조각 간격.

None
donutchart

도넛 차트 여부.

False
wedge_width

도넛 차트일 때 조각 너비 비율.

0.7
wedge_color

도넛 차트일 때 조각 사이 경계선 색상.

'#ffffff'
wedge_linewidth

도넛 차트일 때 조각 사이 경계선 굵기.

3
palette

색상 팔레트 이름.

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def pieplot(x, labels, autopct="%0.1f%%", startangle=90, counterclock=False, 
            explode=None, donutchart=False, 
            wedge_width=0.7, wedge_color="#ffffff", wedge_linewidth=3,
            palette=None, title=None, xlabel=None, ylabel=None,
            width=1280, height=640, save_path=None, ax=None):
    """
    파이 그래프 혹은 도넛 그래프를 그린다

    Args:
        x: x축 범주 컬럼명.
        labels: 파이 조각에 대한 라벨.
        autopct: 퍼센트 표시 형식.
        startangle: 시작 각도.
        counterclock: 시계 반대 방향으로 그릴지 여부.
        explode: 조각 간격.
        donutchart: 도넛 차트 여부.
        wedge_width: 도넛 차트일 때 조각 너비 비율.
        wedge_color: 도넛 차트일 때 조각 사이 경계선 색상.
        wedge_linewidth: 도넛 차트일 때 조각 사이 경계선 굵기.
        palette: 색상 팔레트 이름.
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """

    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # 색상값을 팔레트로부터 추출
    color_list = None
    if palette:
        color_list = sb.color_palette(palette, n_colors=len(labels))

    # 도넛 그래프 그리기 옵션 생성
    wedgeprops = None
    if donutchart:
        wedgeprops={"width": wedge_width, "edgecolor": wedge_color, "linewidth": wedge_linewidth}

    # 파이 그래프 그리기
    ax.pie(x, labels=labels, autopct=autopct, startangle=startangle, 
          counterclock=counterclock, explode=explode, colors=color_list, 
          wedgeprops=wedgeprops)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

stackplot

stackplot(
    data,
    x,
    y,
    hue,
    aggfunc=np.sum,
    orient="v",
    ratio=False,
    text=True,
    text_color="#ffffff",
    text_fontsize=12,
    text_format=None,
    palette=None,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

누적 막대그래프를 그린다

Parameters:

Name Type Description Default
data

시각화할 데이터.

required
x

x축 범주 컬럼명.

required
y

y축 값 컬럼명.

required
hue

범주 구분 컬럼명.

required
aggfunc

누적할 값 계산 함수 (기본값: np.sum).

sum
orient

막대 방향 ('v' 또는 'h').

'v'
ratio

누적값을 비율로 표시할지 여부.

False
text

누적값 텍스트 표시 여부.

True
text_color

누적값 텍스트 색상.

'#ffffff'
text_fontsize

누적값 텍스트 폰트 크기.

12
palette

색상 팔레트 이름.

None
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
def stackplot(data, x, y, hue, aggfunc=np.sum, orient='v', ratio=False,
              text=True, text_color="#ffffff", text_fontsize=12, text_format=None,
              palette=None, title=None, xlabel=None, ylabel=None,
              width=1280, height=640, save_path=None, ax=None):
    """
    누적 막대그래프를 그린다

    Args:
        data: 시각화할 데이터.
        x: x축 범주 컬럼명.
        y: y축 값 컬럼명.
        hue: 범주 구분 컬럼명.
        aggfunc: 누적할 값 계산 함수 (기본값: np.sum).
        orient: 막대 방향 ('v' 또는 'h').
        ratio: 누적값을 비율로 표시할지 여부.
        text: 누적값 텍스트 표시 여부.
        text_color: 누적값 텍스트 색상.
        text_fontsize: 누적값 텍스트 폰트 크기.
        palette: 색상 팔레트 이름.
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """
    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # 데이터 피벗팅 (fill_value=0 --> 결측치를 0으로 채움)후 인덱스를 문자열 카테고리로 변환
    df = pivot_table(data=data, index=x, values=y, columns=hue, aggfunc=aggfunc, fill_value=0)
    df.index = df.index.astype("str").astype("category")

    # 누적값을 비율로 변환하는 경우
    if ratio:
        if text_format is None:                     # 텍스트 포멧이 없다면 강제 지정
            text_format = "{:.1f}%"

        df['sum'] = df.sum(axis=1)                  # 각 행의 합 계산하여 'sum' 열에 저장

        for col in df.columns:                      # 각 열에 대해 누적값을 비율로 변환
            df[col] = df[col] / df['sum'] * 100

        df.drop(columns='sum', inplace=True)        # 'sum' 열 제거

        if orient == 'v':                           # 그래프 방향에 따라 축 범위 설정
            ax.set_ylim(0, 100)
        else:
            ax.set_xlim(0, 100)
    else:
        if text_format is None:                     # 텍스트 포멧이 없다면 강제 지정
            text_format = "{:.1f}"

    # 색상값 생성하기
    color_list = None
    if palette is not None:
        color_list = sb.color_palette(palette, n_colors=len(df.columns))

    # 피벗테이블의 각 열에 대해 누적 막대그래프 그리기
    for i, col in enumerate(df.columns):
        color = None

        if color_list is not None:
            color = color_list[i]

        if orient == 'v':
            ax.bar(df.index, df[col], bottom=df.iloc[:, :i].sum(axis=1), color=color, label=col)
        else:
            ax.barh(df.index, df[col], left=df.iloc[:, :i].sum(axis=1), color=color, label=col)

        # 누적값 텍스트 표시
        if text:
            for j, val in enumerate(df[col]):
                if val == 0:  # 누적값이 0인 경우 텍스트 표시하지 않음
                    continue

                if orient == 'v':
                    ax.text(x=j, y=df.iloc[j, :i].sum() + val / 2, 
                            s=text_format.format(val), ha='center', va='center', 
                            color=text_color, fontsize=text_fontsize)
                else:
                    ax.text(x=df.iloc[j, :i].sum() + val / 2, y=j, 
                            s=text_format.format(val), ha='center', va='center', 
                            color=text_color, fontsize=text_fontsize)

    # 범례 표시
    ax.legend(bbox_to_anchor=(1, 1))

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)   

scatterplot

scatterplot(
    data,
    x,
    y,
    hue=None,
    marker="o",
    color=None,
    size=100,
    edgecolor="#ffffff",
    linewidth=1.5,
    alpha=1,
    palette="tab10",
    outline=True,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
    ax=None,
)

산점도를 그린다

Parameters:

Name Type Description Default
data

시각화할 데이터.

required
x

x축 값 컬럼명.

required
y

y축 값 컬럼명.

required
hue

범주 구분 컬럼명.

None
marker

마커 모양 (기본값: "o").

'o'
color

마커 색상 (hue가 None일 때 적용).

None
size

마커 크기 (기본값: 100).

100
edgecolor

마커 테두리 색상 (기본값: "#ffffff").

'#ffffff'
linewidth

마커 테두리 두께 (기본값: 1.5).

1.5
alpha

마커 투명도 (0~1, 기본값: 1).

1
palette

색상 팔레트 이름.

'tab10'
outline

ConvexHull로 외곽선 그릴지 여부. hue가 지정되었을 때만 작동 (기본값: True).

True
title

그래프 제목.

None
xlabel

x축 레이블.

None
ylabel

y축 레이블.

None
width

캔버스 가로 픽셀.

1280
height

캔버스 세로 픽셀.

640
save_path

이미지 저장 경로.

None
ax

그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.

None
Source code in hossam/my_plot.py
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
def scatterplot(data, x, y, hue=None, marker="o", color=None, size=100, edgecolor="#ffffff", 
                linewidth=1.5, alpha=1, palette="tab10", outline=True,
                title=None, xlabel=None, ylabel=None, 
                width=1280, height=640, save_path=None, ax=None):
    """
    산점도를 그린다

    Args:
        data: 시각화할 데이터.
        x: x축 값 컬럼명.
        y: y축 값 컬럼명.
        hue: 범주 구분 컬럼명.
        marker: 마커 모양 (기본값: "o").
        color: 마커 색상 (hue가 None일 때 적용).
        size: 마커 크기 (기본값: 100).
        edgecolor: 마커 테두리 색상 (기본값: "#ffffff").
        linewidth: 마커 테두리 두께 (기본값: 1.5).
        alpha: 마커 투명도 (0~1, 기본값: 1).
        palette: 색상 팔레트 이름.
        outline: ConvexHull로 외곽선 그릴지 여부. hue가 지정되었을 때만 작동 (기본값: True).
        title: 그래프 제목.
        xlabel: x축 레이블.
        ylabel: y축 레이블.
        width: 캔버스 가로 픽셀.
        height: 캔버스 세로 픽셀.
        save_path: 이미지 저장 경로.
        ax: 그래프를 그릴 Axes 객체. None이면 init 함수로 새로 생성.
    """
    # 그래프 초기화
    fig = None
    if ax is None:
        fig, ax = init(width=width, height=height, title=title, xlabel=xlabel, ylabel=ylabel)

    # 군집을 구분할 분류값이 없다면 palette 옵션이 무의미하므로 None으로 설정
    if hue == None:
        if color is None and palette is not None:
            color = sb.color_palette(palette)[0]

        palette = None
    else:
        color = None

    # 산점도 그리기
    sb.scatterplot(data=data, x=x, y=y,
                   hue=hue,             # 군집을 구분할 분류값이 있는 컬럼명
                   color=color,         # 마커 색상
                   palette=palette,     # 색상 팔레트 설정
                   marker=marker,       # 마커 모양
                   s=size,              # 마커 크기 (기본값=100)
                   edgecolor=edgecolor, # 마커 테두리 색상
                   linewidth=linewidth, # 마커 테두리 두께
                   alpha=alpha,         # 마커 투명도
                   ax=ax)               # 그래프를 그릴 Axes 객체

    # 외곽선 그리기
    if outline and hue is not None:
        plot_hull(data=data, x=x, y=y, hue=hue, palette=palette, ax=ax)

    # 그래프 표시
    if fig is not None:
        show(save_path=save_path)

plot_hull

plot_hull(data, x, y, hue, palette, ax)

ConvexHull을 이용하여 각 군집의 외곽선을 그리는 함수

Parameters:

Name Type Description Default
data

시각화할 데이터.

required
x

x축 값 컬럼명.

required
y

y축 값 컬럼명.

required
hue

범주 구분 컬럼명.

required
palette

색상 팔레트 이름.

required
ax

ConvexHull로 외곽선을 그릴 Axes 객체.

required
Source code in hossam/my_plot.py
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
def plot_hull(data, x, y, hue, palette, ax):
    """
    ConvexHull을 이용하여 각 군집의 외곽선을 그리는 함수

    Args:
        data: 시각화할 데이터.
        x: x축 값 컬럼명.
        y: y축 값 컬럼명.
        hue: 범주 구분 컬럼명.
        palette: 색상 팔레트 이름.
        ax: ConvexHull로 외곽선을 그릴 Axes 객체.
    """

    # 데이터의 군집 종류 얻기
    classes = sorted(list(data[hue].unique()))

    # 각 클래스에 대하여 반복 수행
    for i, v in enumerate(classes):
        # 현재 클래스에 해당하는 데이터 포인트 추출
        df_c = data.loc[data[hue] == v, [x, y]]

        # ConvexHull은 3개 이상의 점이 필요하므로, 데이터 포인트가 3개 미만인 경우 중단해야 함
        if len(df_c) < 3:
            continue

        hull = ConvexHull(df_c)
        points = np.append(hull.vertices, hull.vertices[0])

        # 현재 클래스에 적용될 색상값 생성
        color = sb.color_palette(palette)[i]

        # points를 index로 하는 데이터 포인트를 선과 면으로 표시
        ax.plot(df_c.iloc[points, 0], df_c.iloc[points, 1], linewidth=1, linestyle=":", color=color)
        ax.fill(df_c.iloc[points, 0], df_c.iloc[points, 1], alpha=0.1, color=color)

lmplot

lmplot(
    data,
    x,
    y,
    hue=None,
    palette=None,
    col=None,
    row=None,
    markers="o",
    scatter_edgecolor="#ffffff",
    scatter_linewidths=1,
    scatter_size=50,
    scatter_alpha=0.8,
    linestyle="-",
    linecolor=None,
    linewidth=2,
    title=None,
    xlabel=None,
    ylabel=None,
    width=1280,
    height=640,
    save_path=None,
)

seaborn lmplot으로 산점도 그래프와 회귀선을 시각화 한다.

Parameters:

Name Type Description Default
data DataFrame

시각화할 데이터.

required
x str

독립변수 컬럼.

required
y str

종속변수 컬럼.

required
hue str | None

범주 컬럼.

None
palette str | None

팔레트 이름.

None
col str | None

열 패싯 컬럼.

None
row str | None

행 패싯 컬럼.

None
markers str | list[str]

산점도 점 모양.

'o'
scatter_edgecolor str | None

산점도 점 외곽선 색상.

'#ffffff'
scatter_linewidths float

산점도 점 외곽선 굵기

1
scatter_size int

산점도 점 크기.

50
scatter_alpha float

산점도 점 투명도.

0.8
linestyle str

회귀선 스타일.

'-'
linecolor str | None

회귀선 색상.

None
linewidth float

회귀선 굵기.

2
title str | None

그래프 제목.

None
xlabel str | None

x축 레이블.

None
ylabel str | None

y축 레이블.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

640
save_path str | None

이미지 저장 경로. None이면 화면에 표시.

None

Returns:

Type Description

None

Source code in hossam/my_plot.py
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
def lmplot(data, x, y, hue=None, palette=None, col=None, row=None, markers="o",
    scatter_edgecolor="#ffffff", scatter_linewidths=1, scatter_size=50, 
    scatter_alpha= 0.8, linestyle="-", linecolor=None, linewidth= 2,
    title= None, xlabel= None, ylabel= None, width=1280, height=640,
    save_path= None):
    """
    seaborn lmplot으로 산점도 그래프와 회귀선을 시각화 한다.

    Args:
        data (DataFrame): 시각화할 데이터.
        x (str): 독립변수 컬럼.
        y (str): 종속변수 컬럼.
        hue (str|None): 범주 컬럼.
        palette (str|None): 팔레트 이름.
        col (str|None): 열 패싯 컬럼.
        row (str|None): 행 패싯 컬럼.
        markers (str|list[str]): 산점도 점 모양.
        scatter_edgecolor (str|None): 산점도 점 외곽선 색상.
        scatter_linewidths (float): 산점도 점 외곽선 굵기
        scatter_size (int): 산점도 점 크기.
        scatter_alpha (float): 산점도 점 투명도.
        linestyle (str): 회귀선 스타일.
        linecolor (str|None): 회귀선 색상.
        linewidth (float): 회귀선 굵기.
        title (str|None): 그래프 제목.
        xlabel (str|None): x축 레이블.
        ylabel (str|None): y축 레이블.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        save_path (str|None): 이미지 저장 경로. None이면 화면에 표시.

    Returns:
        None
    """
    # 1) 그래프 초기화
    w = width / 100             # 가로 크기
    h = height / 100            # 세로 크기
    my_dpi = 200                # 해상도 설정

    # hue가 지정되지 않았는데 palette와 linecolor가 지정된 경우, 무의미하므로 None으로 설정
    if not hue and palette:
        palette = None
        linecolor = None

    # 2) lmplot 그리기
    g = sb.lmplot(data=data, x=x,  y=y, 
                height=h,            # 그래프의 높이
                aspect=w/h,          # 그래프의 가로 세로 비율 (width/height)
                hue=hue,             # 종별로 색상 구분
                col=col,             # 열 분할
                row=row,             # 행 분할
                legend=False,        # 범례 제거 (그래프와 겹치기 때문에 수동 설정 권장)
                markers=markers,     # 마커 모양 개수가 범주의 수와 일치하도록 설정
                palette=palette,     # 색상 팔레트 설정 가능함
                scatter_kws={
                        "edgecolor": scatter_edgecolor,
                        "linewidths": scatter_linewidths,
                        "s": scatter_size,
                        "alpha": scatter_alpha
                },
                line_kws={
                        "linestyle": linestyle,
                        "color": linecolor,
                        "linewidth": linewidth
                }
    )

    # 3) 그래프 설정 및 표시
    g.fig.set_dpi(my_dpi)
    g.fig.set_tight_layout(True)

    if title:
        g.fig.suptitle(title, fontsize=24, fontweight=500, y=1)

    for x in g.axes.flatten():
        x.grid(True, alpha=0.5)
        x.set_axisbelow(True)

        if xlabel:
            x.set_xlabel(xlabel, fontsize=16, fontweight=400, labelpad=5)

        if ylabel:
            x.set_ylabel(ylabel, fontsize=16, fontweight=400, labelpad=5)

        if hue is not None:
            x.legend(bbox_to_anchor=(1, 1), loc='upper left') # 범례 위치 조정

    show(save_path=save_path)

pairplot

pairplot(
    data,
    x=None,
    y=None,
    hue=None,
    palette=None,
    diag_kind="kde",
    reg=False,
    markers="o",
    scatter_size=20,
    scatter_alpha=0.8,
    linecolor=None,
    linewidth=1.5,
    linestyle="-",
    title=None,
    width=1280,
    height=640,
    save_path=None,
)

산점도 행렬 시각화

Parameters:

Name Type Description Default
data DataFrame

시각화할 데이터.

required
x str | list[str] | None

대상 컬럼명 혹은 컬럼명 리스트

None
y str | list[str] | None

대상 컬럼명 혹은 컬럼명 리스트

None
hue str | None

범주 컬럼명.

None
palette str | None

팔레트 이름.

None
diag_kind str

대각선에 표시할 그래프 종류. 'hist' 또는 'kde'.

'kde'
reg bool

회귀선 표시 여부.

False
markers str | list[str]

산점도 점 모양.

'o'
scatter_size int

산점도 점 크기.

20
scatter_alpha float

산점도 점 투명도.

0.8
linecolor str | None

회귀선 색상.

None
linewidth float

회귀선 굵기.

1.5
linestyle str

회귀선 스타일.

'-'
title str | None

그래프 제목.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

640
save_path str | None

이미지 저장 경로. None이면 화면에 표시.

None
Source code in hossam/my_plot.py
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
def pairplot(data, x=None, y=None, hue=None, palette=None, diag_kind="kde", reg=False, 
             markers="o", scatter_size=20, scatter_alpha=0.8, 
             linecolor=None, linewidth=1.5, linestyle="-",
             title=None, width=1280, height=640, save_path=None):
    """
    산점도 행렬 시각화

    Args:
        data (DataFrame): 시각화할 데이터.
        x (str|list[str]|None): 대상 컬럼명 혹은 컬럼명 리스트
        y (str|list[str]|None): 대상 컬럼명 혹은 컬럼명 리스트
        hue (str|None): 범주 컬럼명.
        palette (str|None): 팔레트 이름.
        diag_kind (str): 대각선에 표시할 그래프 종류. 'hist' 또는 'kde'.
        reg (bool): 회귀선 표시 여부.
        markers (str|list[str]): 산점도 점 모양.
        scatter_size (int): 산점도 점 크기.
        scatter_alpha (float): 산점도 점 투명도.
        linecolor (str|None): 회귀선 색상.
        linewidth (float): 회귀선 굵기.
        linestyle (str): 회귀선 스타일.
        title (str|None): 그래프 제목.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        save_path (str|None): 이미지 저장 경로. None이면 화면에 표시.
    """
    # 1) 그래프 초기화
    figsize = (width / 100, height / 100)

    # hue가 지정되지 않았는데 palette와 linecolor가 지정된 경우, 무의미하므로 None으로 설정
    if not hue and palette:
        palette = None

    # 회귀선의 표시 여부에 따라서 plot_kws 분기
    if reg:
        plot_kws = {
            "scatter_kws": { "s": scatter_size, "alpha": scatter_alpha},
            "line_kws": { "color": linecolor, "linewidth": linewidth, "linestyle": linestyle}
        }
    else:
        plot_kws = { "s": scatter_size, "alpha": scatter_alpha }

    # 2) pairplot 그리기
    g = sb.pairplot(data=data, hue=hue, markers=markers, palette=palette,
                    kind="reg" if reg else "scatter", 
                    diag_kind=diag_kind, plot_kws=plot_kws)

    g.fig.set_dpi(200)
    g.fig.set_figwidth(figsize[0])
    g.fig.set_figheight(figsize[1])

    if title:
        g.fig.suptitle(title, fontsize=24, fontweight='bold')

    # 3) 개별 그래프 설정 및 화면 출력
    for ax in g.axes.flatten():
        ax.set_axisbelow(True)    # 격자를 그래프 뒤로 이동
        ax.grid(True, alpha=0.5)  # 격자 추가

    show(save_path)               # 화면 출력