콘텐츠로 이동

hossam.plot

hossam.plot

hs_lineplot

hs_lineplot(
    df,
    xname=None,
    yname=None,
    hue=None,
    marker=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

선 그래프를 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str | None

x축 컬럼명.

None
yname str | None

y축 컬럼명.

None
hue str | None

범주 구분 컬럼명.

None
marker str | None

마커 모양.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn lineplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
 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
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
def hs_lineplot(
    df: DataFrame,
    xname: str = None,
    yname: str = None,
    hue: str = None,
    marker: str = None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """선 그래프를 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str|None): x축 컬럼명.
        yname (str|None): y축 컬럼명.
        hue (str|None): 범주 구분 컬럼명.
        marker (str|None): 마커 모양.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn lineplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.lineplot(
        data=df,
        x=xname,
        y=yname,
        hue=hue,
        marker=marker,
        palette=palette,
        ax=ax,
        **params,
    )
    ax.grid()
    _finalize_plot(ax, callback, outparams)

hs_boxplot

hs_boxplot(
    df,
    xname=None,
    yname=None,
    orient="v",
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

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

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str | None

x축 범주 컬럼명.

None
yname str | None

y축 값 컬럼명.

None
orient str

'v' 또는 'h' 방향.

'v'
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn boxplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def hs_boxplot(
    df: DataFrame,
    xname: str = None,
    yname: str = None,
    orient: str = "v",
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """상자그림(boxplot)을 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str|None): x축 범주 컬럼명.
        yname (str|None): y축 값 컬럼명.
        orient (str): 'v' 또는 'h' 방향.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn boxplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    if xname is not None and yname is not None:
        sb.boxplot(
            data=df, x=xname, y=yname, orient=orient, palette=palette, ax=ax, **params
        )
    else:
        sb.boxplot(data=df, orient=orient, ax=ax, **params)

    ax.grid()
    _finalize_plot(ax, callback, outparams)

hs_kdeplot

hs_kdeplot(
    df,
    xname=None,
    yname=None,
    hue=None,
    palette=None,
    fill=False,
    fill_alpha=0.3,
    linewidth=1,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

커널 밀도 추정(KDE) 그래프를 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str | None

x축 컬럼명.

None
yname str | None

y축 컬럼명.

None
hue str | None

범주 컬럼명.

None
palette str | None

팔레트 이름.

None
fill bool

면적 채우기 여부.

False
fill_alpha float

채움 투명도.

0.3
linewidth float

선 굵기.

1
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn kdeplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def hs_kdeplot(
    df: DataFrame,
    xname: str = None,
    yname: str = None,
    hue: str = None,
    palette: str = None,
    fill: bool = False,
    fill_alpha: float = 0.3,
    linewidth: float = 1,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """커널 밀도 추정(KDE) 그래프를 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str|None): x축 컬럼명.
        yname (str|None): y축 컬럼명.
        hue (str|None): 범주 컬럼명.
        palette (str|None): 팔레트 이름.
        fill (bool): 면적 채우기 여부.
        fill_alpha (float): 채움 투명도.
        linewidth (float): 선 굵기.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn kdeplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    # 기본 kwargs 설정
    kdeplot_kwargs = {
        "data": df,
        "x": xname,
        "y": yname,
        "hue": hue,
        "fill": fill,
        "ax": ax,
    }

    # fill이 True일 때 alpha 추가
    if fill:
        kdeplot_kwargs["alpha"] = fill_alpha

    # hue가 있을 때만 palette 추가
    if hue is not None and palette is not None:
        kdeplot_kwargs["palette"] = palette

    # yname이 없을 때만 linewidth 추가 (1D KDE에서만 사용)
    if yname is None:
        kdeplot_kwargs["linewidth"] = linewidth

    # 추가 params 병합
    kdeplot_kwargs.update(params)

    sb.kdeplot(**kdeplot_kwargs)

    # plt.grid()
    ax.grid()
    _finalize_plot(ax, callback, outparams)

hs_histplot

hs_histplot(
    df,
    xname,
    hue=None,
    bins=None,
    kde=True,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

히스토그램을 그리고 필요 시 KDE를 함께 표시한다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

히스토그램 대상 컬럼명.

required
hue str | None

범주 컬럼명.

None
bins int | sequence | None

구간 수 또는 경계.

None
kde bool

KDE 표시 여부.

True
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn histplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
258
259
260
261
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
303
304
305
306
307
308
309
310
311
312
313
314
def hs_histplot(
    df: DataFrame,
    xname: str,
    hue=None,
    bins=None,
    kde: bool = True,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """히스토그램을 그리고 필요 시 KDE를 함께 표시한다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): 히스토그램 대상 컬럼명.
        hue (str|None): 범주 컬럼명.
        bins (int|sequence|None): 구간 수 또는 경계.
        kde (bool): KDE 표시 여부.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn histplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    if bins:
        sb.histplot(
            data=df,
            x=xname,
            hue=hue,
            kde=kde,
            bins=bins,
            palette=palette,
            ax=ax,
            **params,
        )
    else:
        sb.histplot(
            data=df, x=xname, hue=hue, kde=kde, palette=palette, ax=ax, **params
        )

    # plt.grid()
    _finalize_plot(ax, callback, outparams)

hs_stackplot

hs_stackplot(
    df,
    xname,
    hue,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

클래스 비율을 100% 누적 막대로 표현한다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

x축 기준 컬럼.

required
hue str

클래스 컬럼.

required
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn histplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
355
356
357
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
def hs_stackplot(
    df: DataFrame,
    xname: str,
    hue: str,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """클래스 비율을 100% 누적 막대로 표현한다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): x축 기준 컬럼.
        hue (str): 클래스 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn histplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    df2 = df[[xname, hue]].copy()
    df2[xname] = df2[xname].astype(str)

    sb.histplot(
        data=df2,
        x=xname,
        hue=hue,
        palette=palette,
        linewidth=0.5,
        stat="probability",  # 전체에서의 비율로 그리기
        multiple="fill",  # 전체를 100%로 그리기
        shrink=0.8,  # 막대의 폭
        ax=ax,
        **params,
    )

    # 그래프의 x축 항목 수 만큼 반복
    for p in ax.patches:
        # 각 막대의 위치, 넓이, 높이
        left, bottom, width, height = p.get_bbox().bounds
        # 막대의 중앙에 글자 표시하기
        ax.annotate(
            "%0.1f%%" % (height * 100),
            xy=(left + width / 2, bottom + height / 2),
            ha="center",
            va="center",
        )

    # plt.grid()

    if str(df[xname].dtype) in ["int", "int32", "int64", "float", "float32", "float64"]:
        xticks = list(df[xname].unique())
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticks)

    _finalize_plot(ax, callback, outparams)

hs_scatterplot

hs_scatterplot(
    df,
    xname,
    yname,
    hue=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

산점도를 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

x축 컬럼.

required
yname str

y축 컬럼.

required
hue str | None

범주 컬럼.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn scatterplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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
def hs_scatterplot(
    df: DataFrame,
    xname: str,
    yname: str,
    hue=None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """산점도를 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): x축 컬럼.
        yname (str): y축 컬럼.
        hue (str|None): 범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn scatterplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.scatterplot(data=df, x=xname, y=yname, hue=hue, palette=palette, ax=ax, **params)
    ax.grid()

    _finalize_plot(ax, callback, outparams)

hs_regplot

hs_regplot(
    df,
    xname,
    yname,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

단순 회귀선이 포함된 산점도를 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

독립변수 컬럼.

required
yname str

종속변수 컬럼.

required
palette str | None

선/점 색상.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn regplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
436
437
438
439
440
441
442
443
444
445
446
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
def hs_regplot(
    df: DataFrame,
    xname: str,
    yname: str,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """단순 회귀선이 포함된 산점도를 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): 독립변수 컬럼.
        yname (str): 종속변수 컬럼.
        palette (str|None): 선/점 색상.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn regplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.regplot(data=df, x=xname, y=yname, scatter_kws={"color": palette},
                line_kws={
                    "color": "red",
                    "linestyle": "--",
                    "linewidth": 2
                }, ax=ax, **params)
    ax.grid()

    _finalize_plot(ax, callback, outparams)

hs_lmplot

hs_lmplot(
    df,
    xname,
    yname,
    hue=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    **params
)

seaborn lmplot으로 선형 모델 시각화를 수행한다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

독립변수 컬럼.

required
yname str

종속변수 컬럼.

required
hue str | None

범주 컬럼.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
**params

seaborn lmplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
def hs_lmplot(
    df: DataFrame,
    xname: str,
    yname: str,
    hue=None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    **params,
) -> None:
    """seaborn lmplot으로 선형 모델 시각화를 수행한다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): 독립변수 컬럼.
        yname (str): 종속변수 컬럼.
        hue (str|None): 범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        **params: seaborn lmplot 추가 인자.

    Returns:
        None
    """
    g = sb.lmplot(data=df, x=xname, y=yname, hue=hue, palette=palette, **params)
    g.fig.set_size_inches(width / dpi, height / dpi)
    g.fig.set_dpi(dpi)
    g.ax.grid()
    plt.tight_layout()
    plt.show()
    plt.close()

hs_pairplot

hs_pairplot(
    df,
    diag_kind="kde",
    hue=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    **params
)

모든 숫자형/지정 컬럼 쌍에 대한 관계를 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
diag_kind str

대각선 플롯 종류('kde' 등).

'kde'
hue str | None

범주 컬럼.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

기본 크기 및 해상도(컬럼 수에 비례해 확대됨).

200
**params

seaborn pairplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
546
547
548
549
550
551
552
553
def hs_pairplot(
    df: DataFrame,
    diag_kind: str = "kde",
    hue=None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    **params,
) -> None:
    """모든 숫자형/지정 컬럼 쌍에 대한 관계를 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        diag_kind (str): 대각선 플롯 종류('kde' 등).
        hue (str|None): 범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 기본 크기 및 해상도(컬럼 수에 비례해 확대됨).
        **params: seaborn pairplot 추가 인자.

    Returns:
        None
    """
    g = sb.pairplot(data=df, hue=hue, diag_kind=diag_kind, palette=palette, **params)
    scale = len(df.columns)
    g.fig.set_size_inches(w=(width / dpi) * scale, h=(height / dpi) * scale)
    g.fig.set_dpi(dpi)
    g.map_lower(func=sb.kdeplot, fill=True, alpha=0.3)
    g.map_upper(func=sb.scatterplot)
    plt.tight_layout()
    plt.show()
    plt.close()

hs_countplot

hs_countplot(
    df,
    xname,
    hue=None,
    palette=None,
    order=1,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

범주 빈도 막대그래프를 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

범주 컬럼.

required
hue str | None

보조 범주 컬럼.

None
palette str | None

팔레트 이름.

None
order int

숫자형일 때 정렬 방식(1: 값 기준, 기타: 빈도 기준).

1
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn countplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
602
603
604
605
def hs_countplot(
    df: DataFrame,
    xname: str,
    hue=None,
    palette: str = None,
    order: int = 1,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """범주 빈도 막대그래프를 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): 범주 컬럼.
        hue (str|None): 보조 범주 컬럼.
        palette (str|None): 팔레트 이름.
        order (int): 숫자형일 때 정렬 방식(1: 값 기준, 기타: 빈도 기준).
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn countplot 추가 인자.

    Returns:
        None
    """
    outparams = False
    sort = None
    if str(df[xname].dtype) in ["int", "int32", "int64", "float", "float32", "float64"]:
        if order == 1:
            sort = sorted(list(df[xname].unique()))
        else:
            sort = sorted(list(df[xname].value_counts().index))

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.countplot(
        data=df, x=xname, hue=hue, palette=palette, order=sort, ax=ax, **params
    )
    ax.grid()

    _finalize_plot(ax, callback, outparams)

hs_barplot

hs_barplot(
    df,
    xname,
    yname,
    hue=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

막대그래프를 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

범주 컬럼.

required
yname str

값 컬럼.

required
hue str | None

보조 범주 컬럼.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn barplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
def hs_barplot(
    df: DataFrame,
    xname: str,
    yname: str,
    hue=None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """막대그래프를 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): 범주 컬럼.
        yname (str): 값 컬럼.
        hue (str|None): 보조 범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn barplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.barplot(data=df, x=xname, y=yname, hue=hue, palette=palette, ax=ax, **params)
    ax.grid()

    _finalize_plot(ax, callback, outparams)

hs_boxenplot

hs_boxenplot(
    df,
    xname,
    yname,
    hue=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

박스앤 위스커 확장(boxen) 플롯을 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

범주 컬럼.

required
yname str

값 컬럼.

required
hue str | None

보조 범주 컬럼.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn boxenplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
700
701
702
703
704
705
706
707
def hs_boxenplot(
    df: DataFrame,
    xname: str,
    yname: str,
    hue=None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """박스앤 위스커 확장(boxen) 플롯을 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): 범주 컬럼.
        yname (str): 값 컬럼.
        hue (str|None): 보조 범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn boxenplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    # palette은 hue가 있을 때만 사용
    boxenplot_kwargs = {
        "data": df,
        "x": xname,
        "y": yname,
        "hue": hue,
        "ax": ax,
    }

    if hue is not None and palette is not None:
        boxenplot_kwargs["palette"] = palette

    boxenplot_kwargs.update(params)

    sb.boxenplot(**boxenplot_kwargs)
    ax.grid()

    _finalize_plot(ax, callback, outparams)

hs_violinplot

hs_violinplot(
    df,
    xname,
    yname,
    hue=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

바이올린 플롯을 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

범주 컬럼.

required
yname str

값 컬럼.

required
hue str | None

보조 범주 컬럼.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn violinplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
765
def hs_violinplot(
    df: DataFrame,
    xname: str,
    yname: str,
    hue=None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """바이올린 플롯을 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): 범주 컬럼.
        yname (str): 값 컬럼.
        hue (str|None): 보조 범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn violinplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    # palette은 hue가 있을 때만 사용
    violinplot_kwargs = {
        "data": df,
        "x": xname,
        "y": yname,
        "hue": hue,
        "ax": ax,
    }

    if hue is not None and palette is not None:
        violinplot_kwargs["palette"] = palette

    violinplot_kwargs.update(params)

    sb.violinplot(**violinplot_kwargs)
    ax.grid()

    _finalize_plot(ax, callback, outparams)

hs_pointplot

hs_pointplot(
    df,
    xname,
    yname,
    hue=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

포인트 플롯을 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

범주 컬럼.

required
yname str

값 컬럼.

required
hue str | None

보조 범주 컬럼.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn pointplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/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
803
804
805
806
807
808
809
def hs_pointplot(
    df: DataFrame,
    xname: str,
    yname: str,
    hue=None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """포인트 플롯을 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): 범주 컬럼.
        yname (str): 값 컬럼.
        hue (str|None): 보조 범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn pointplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.pointplot(data=df, x=xname, y=yname, hue=hue, palette=palette, ax=ax, **params)
    ax.grid()

    _finalize_plot(ax, callback, outparams)

hs_jointplot

hs_jointplot(
    df,
    xname,
    yname,
    hue=None,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    **params
)

공동 분포(joint) 플롯을 그린다.

Parameters:

Name Type Description Default
df DataFrame

시각화할 데이터.

required
xname str

x축 컬럼.

required
yname str

y축 컬럼.

required
hue str | None

범주 컬럼.

None
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
**params

seaborn jointplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
def hs_jointplot(
    df: DataFrame,
    xname: str,
    yname: str,
    hue=None,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    **params,
) -> None:
    """공동 분포(joint) 플롯을 그린다.

    Args:
        df (DataFrame): 시각화할 데이터.
        xname (str): x축 컬럼.
        yname (str): y축 컬럼.
        hue (str|None): 범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        **params: seaborn jointplot 추가 인자.

    Returns:
        None
    """
    g = sb.jointplot(data=df, x=xname, y=yname, hue=hue, palette=palette, **params)
    g.fig.set_size_inches(width / dpi, height / dpi)
    g.fig.set_dpi(dpi)

    # 중앙 및 주변 플롯에 grid 추가
    g.ax_joint.grid(True, alpha=0.3)
    g.ax_marg_x.grid(True, alpha=0.3)
    g.ax_marg_y.grid(True, alpha=0.3)

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

hs_heatmap

hs_heatmap(
    data,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

히트맵을 그린다(값 주석 포함).

Parameters:

Name Type Description Default
data DataFrame

행렬 형태 데이터.

required
palette str | None

컬러맵 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn heatmap 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
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
def hs_heatmap(
    data: DataFrame,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """히트맵을 그린다(값 주석 포함).

    Args:
        data (DataFrame): 행렬 형태 데이터.
        palette (str|None): 컬러맵 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn heatmap 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.heatmap(data, annot=True, cmap=palette, fmt=".2f", ax=ax, **params)

    _finalize_plot(ax, callback, outparams)

hs_convex_hull

hs_convex_hull(
    data,
    xname,
    yname,
    hue,
    palette=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

클러스터별 볼록 껍질(convex hull)과 산점도를 그린다.

Parameters:

Name Type Description Default
data DataFrame

시각화할 데이터.

required
xname str

x축 컬럼.

required
yname str

y축 컬럼.

required
hue str

클러스터/범주 컬럼.

required
palette str | None

팔레트 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn scatterplot 추가 인자.

{}

Returns:

Type Description

None

Source code in hossam/plot.py
892
893
894
895
896
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
def hs_convex_hull(
    data: DataFrame,
    xname: str,
    yname: str,
    hue: str,
    palette: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
):
    """클러스터별 볼록 껍질(convex hull)과 산점도를 그린다.

    Args:
        data (DataFrame): 시각화할 데이터.
        xname (str): x축 컬럼.
        yname (str): y축 컬럼.
        hue (str): 클러스터/범주 컬럼.
        palette (str|None): 팔레트 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn scatterplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    # 군집별 값의 종류별로 반복 수행
    for c in data[hue].unique():
        if c == -1:
            continue

        # 한 종류만 필터링한 결과에서 두 변수만 선택
        df_c = data.loc[data[hue] == c, [xname, yname]]

        try:
            # 외각선 좌표 계산
            hull = ConvexHull(df_c)

            # 마지막 좌표 이후에 첫 번째 좌표를 연결
            points = np.append(hull.vertices, hull.vertices[0])

            ax.plot(
                df_c.iloc[points, 0], df_c.iloc[points, 1], linewidth=1, linestyle=":"
            )
            ax.fill(df_c.iloc[points, 0], df_c.iloc[points, 1], alpha=0.1)
        except:
            pass

    sb.scatterplot(
        data=data, x=xname, y=yname, hue=hue, palette=palette, ax=ax, **params
    )
    ax.grid()
    _finalize_plot(ax, callback, outparams)

hs_kde_confidence_interval

hs_kde_confidence_interval(
    data,
    clevel=0.95,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
)

각 숫자 컬럼에 대해 KDE와 t-분포 기반 신뢰구간을 그린다.

Parameters:

Name Type Description Default
data DataFrame

시각화할 데이터.

required
clevel float

신뢰수준(0~1).

0.95
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None

Returns:

Type Description
None

None

Source code in hossam/plot.py
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
def hs_kde_confidence_interval(
    data: DataFrame,
    clevel=0.95,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
) -> None:
    """각 숫자 컬럼에 대해 KDE와 t-분포 기반 신뢰구간을 그린다.

    Args:
        data (DataFrame): 시각화할 데이터.
        clevel (float): 신뢰수준(0~1).
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.

    Returns:
        None
    """
    outparams = False
    y_min, y_max = None, None

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    # 데이터 프레임의 컬럼이 여러 개인 경우 처리
    for c in data.columns:
        column = data[c].dropna()
        if len(column) < 2:
            continue
        # print(column)
        dof = len(column) - 1  # 자유도
        sample_mean = column.mean()  # 표본평균
        sample_std = column.std(ddof=1)  # 표본표준편차
        sample_std_error = sample_std / sqrt(len(column))  # 표본표준오차
        # print(max, dof, sample_mean, sample_std, sample_std_error)

        # 신뢰구간
        cmin, cmax = t.interval(clevel, dof, loc=sample_mean, scale=sample_std_error)
        # print(cmin, cmax)

        # 현재 컬럼에 대한 커널밀도추정
        sb.kdeplot(data=column, ax=ax)

        # 그래프 축의 범위
        xmin, xmax, ymin, ymax = plt.axis()
        y_min = ymin if y_min is None else min(y_min, ymin)
        y_max = ymax if y_max is None else max(y_max, ymax)

        # 신뢰구간 그리기
        ax.plot([cmin, cmin], [ymin, ymax], linestyle=":")
        ax.plot([cmax, cmax], [ymin, ymax], linestyle=":")
        # print([cmin, cmax])
        ax.fill_between([cmin, cmax], y1=ymin, y2=ymax, alpha=0.1)

        # 평균 그리기
        ax.plot([sample_mean, sample_mean], [0, ymax], linestyle="--", linewidth=2)

        ax.text(
            x=(cmax - cmin) / 2 + cmin,
            y=ymax,
            s="[%s] %0.1f ~ %0.1f" % (column.name, cmin, cmax),
            horizontalalignment="center",
            verticalalignment="bottom",
            fontdict={"size": 7, "color": "red"},
        )

    if y_min is not None and y_max is not None:
        ax.set_ylim([y_min, y_max * 1.1])
    ax.grid()
    _finalize_plot(ax, callback, outparams)

hs_pvalue1_anotation

hs_pvalue1_anotation(
    data,
    target,
    hue,
    pairs,
    test="t-test_ind",
    text_format="star",
    loc="outside",
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
)

statannotations를 이용해 상자그림에 p-value 주석을 추가한다.

Parameters:

Name Type Description Default
data DataFrame

시각화할 데이터.

required
target str

값 컬럼명.

required
hue str

그룹 컬럼명.

required
pairs list

비교할 (group_a, group_b) 튜플 목록.

required
test str

적용할 통계 검정 이름.

't-test_ind'
text_format str

주석 형식('star' 등).

'star'
loc str

주석 위치.

'outside'
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None

Returns:

Type Description
None

None

Source code in hossam/plot.py
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
def hs_pvalue1_anotation(
    data: DataFrame,
    target: str,
    hue: str,
    pairs: list,
    test: str = "t-test_ind",
    text_format: str = "star",
    loc: str = "outside",
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
) -> None:
    """statannotations를 이용해 상자그림에 p-value 주석을 추가한다.

    Args:
        data (DataFrame): 시각화할 데이터.
        target (str): 값 컬럼명.
        hue (str): 그룹 컬럼명.
        pairs (list): 비교할 (group_a, group_b) 튜플 목록.
        test (str): 적용할 통계 검정 이름.
        text_format (str): 주석 형식('star' 등).
        loc (str): 주석 위치.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.boxplot(data=data, x=hue, y=target, ax=ax)

    annotator = Annotator(ax, data=data, x=hue, y=target, pairs=pairs)
    annotator.configure(test=test, text_format=text_format, loc=loc)
    annotator.apply_and_annotate()

    sb.despine()

    _finalize_plot(ax, callback, outparams)

hs_residplot

hs_residplot(
    y,
    y_pred,
    lowess=False,
    mse=False,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

잔차 대 예측치 산점도를 그린다(선택적으로 MSE 범위와 LOWESS 포함).

Parameters:

Name Type Description Default
y array - like

실제 값.

required
y_pred array - like

예측 값.

required
lowess bool

LOWESS 스무딩 적용 여부.

False
mse bool

√MSE, 2√MSE, 3√MSE 대역선과 비율 표시 여부.

False
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn residplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
def hs_residplot(
    y,
    y_pred,
    lowess: bool = False,
    mse: bool = False,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """잔차 대 예측치 산점도를 그린다(선택적으로 MSE 범위와 LOWESS 포함).

    Args:
        y (array-like): 실제 값.
        y_pred (array-like): 예측 값.
        lowess (bool): LOWESS 스무딩 적용 여부.
        mse (bool): √MSE, 2√MSE, 3√MSE 대역선과 비율 표시 여부.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn residplot 추가 인자.

    Returns:
        None
    """
    outparams = False
    resid = y - y_pred

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    sb.residplot(
        x=y_pred,
        y=resid,
        lowess=lowess,
        line_kws={"color": "red", "linewidth": 1},
        scatter_kws={"edgecolor": "white", "alpha": 0.7},
        ax=ax,
        **params,
    )

    if mse:
        mse_val = mean_squared_error(y, y_pred)
        mse_sq = np.sqrt(mse_val)

        r1 = resid[(resid > -mse_sq) & (resid < mse_sq)].size / resid.size * 100
        r2 = (
            resid[(resid > -2 * mse_sq) & (resid < 2 * mse_sq)].size
            / resid.size
            * 100
        )
        r3 = (
            resid[(resid > -3 * mse_sq) & (resid < 3 * mse_sq)].size
            / resid.size
            * 100
        )

        mse_r = [r1, r2, r3]

        xmin, xmax = ax.get_xlim()

        # 구간별 반투명 색상 채우기 (안쪽부터 바깥쪽으로, 진한 색에서 연한 색으로)
        colors = ["red", "green", "blue"]
        alphas = [0.15, 0.10, 0.05]  # 안쪽이 더 진하게

        # 3σ 영역 (가장 바깥쪽, 가장 연함)
        ax.axhspan(-3 * mse_sq, 3 * mse_sq, facecolor=colors[2], alpha=alphas[2], zorder=0)
        # 2σ 영역 (중간)
        ax.axhspan(-2 * mse_sq, 2 * mse_sq, facecolor=colors[1], alpha=alphas[1], zorder=1)
        # 1σ 영역 (가장 안쪽, 가장 진함)
        ax.axhspan(-mse_sq, mse_sq, facecolor=colors[0], alpha=alphas[0], zorder=2)

        # 경계선 그리기
        for i, c in enumerate(["red", "green", "blue"]):
            ax.axhline(mse_sq * (i + 1), color=c, linestyle="--", linewidth=0.5)
            ax.axhline(mse_sq * (-(i + 1)), color=c, linestyle="--", linewidth=0.5)

        target = [68, 95, 99]
        for i, c in enumerate(["red", "green", "blue"]):
            ax.text(
                s=f"{i+1} sqrt(MSE) = {mse_r[i]:.2f}% ({mse_r[i] - target[i]:.2f}%)",
                x=xmax + 0.2,
                y=(i + 1) * mse_sq,
                color=c,
            )
            ax.text(
                s=f"-{i+1} sqrt(MSE) = {mse_r[i]:.2f}% ({mse_r[i] - target[i]:.2f}%)",
                x=xmax + 0.2,
                y=-(i + 1) * mse_sq,
                color=c,
            )
    ax.grid()
    _finalize_plot(ax, callback, outparams)

hs_qqplot

hs_qqplot(
    y_pred,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

표준화된 예측값의 정규성 확인을 위한 QQ 플롯을 그린다.

Parameters:

Name Type Description Default
y_pred array - like

예측 값.

required
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

seaborn scatterplot 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def hs_qqplot(
    y_pred,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """표준화된 예측값의 정규성 확인을 위한 QQ 플롯을 그린다.

    Args:
        y_pred (array-like): 예측 값.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: seaborn scatterplot 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    # probplot은 내부적으로 정규화를 수행하므로 zscore를 미리 적용하면 안됨
    (x, y), _ = probplot(y_pred)
    k = (max(x) + 0.5).round()

    sb.scatterplot(x=x, y=y, ax=ax, **params)
    sb.lineplot(x=[-k, k], y=[-k, k], color="red", linestyle="--", ax=ax)
    ax.grid()
    _finalize_plot(ax, callback, outparams)

hs_confusion_matrix

hs_confusion_matrix(
    y,
    y_pred,
    cmap=None,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
    ax=None,
    **params
)

예측 결과에 대한 혼동행렬을 표시한다.

Parameters:

Name Type Description Default
y ndarray | Series

실제 레이블.

required
y_pred ndarray | Series

예측 레이블.

required
cmap str | None

컬러맵 이름.

None
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None
ax Axes | None

외부에서 전달한 Axes.

None
**params

ConfusionMatrixDisplay.from_predictions 추가 인자.

{}

Returns:

Type Description
None

None

Source code in hossam/plot.py
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
def hs_confusion_matrix(
    y: np.ndarray,
    y_pred: np.ndarray,
    cmap: str = None,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
    ax: Axes = None,
    **params,
) -> None:
    """예측 결과에 대한 혼동행렬을 표시한다.

    Args:
        y (ndarray|Series): 실제 레이블.
        y_pred (ndarray|Series): 예측 레이블.
        cmap (str|None): 컬러맵 이름.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.
        ax (Axes|None): 외부에서 전달한 Axes.
        **params: ConfusionMatrixDisplay.from_predictions 추가 인자.

    Returns:
        None
    """
    outparams = False

    if ax is None:
        fig, ax = __get_default_ax(width, height, 1, 1, dpi)
        outparams = True

    # 이진분류인지 다항분류인지 구분
    if hasattr(y, "unique"):
        labels = sorted(list(y.unique()))
    else:
        labels = sorted(list(set(y)))

    # 다중 로지스틱을 살펴볼 때 함수 파라미터 설정이 변경될 수 있다.
    ConfusionMatrixDisplay.from_predictions(
        y,  # 관측치
        y_pred,  # 예측치
        display_labels=labels,
        cmap=cmap,
        text_kw={"fontsize": 24, "weight": "bold"},
        ax=ax,
        **params,
    )

    _finalize_plot(ax, callback, outparams)

hs_distribution_by_class

hs_distribution_by_class(
    data,
    xnames=None,
    hue=None,
    type="kde",
    bins=5,
    palette=None,
    fill=False,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
)

클래스별로 각 숫자형 특징의 분포를 KDE 또는 히스토그램으로 그린다.

Parameters:

Name Type Description Default
data DataFrame

시각화할 데이터.

required
xnames list | None

대상 컬럼 목록(None이면 전 컬럼).

None
hue str | None

클래스 컬럼.

None
type str

'kde' | 'hist' | 'histkde'.

'kde'
bins int | sequence | None

히스토그램 구간.

5
palette str | None

팔레트 이름.

None
fill bool

KDE 채움 여부.

False
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None

Returns:

Type Description
None

None

Source code in hossam/plot.py
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
def hs_distribution_by_class(
    data: DataFrame,
    xnames: list = None,
    hue: str = None,
    type: str = "kde",
    bins: any = 5,
    palette: str = None,
    fill: bool = False,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
) -> None:
    """클래스별로 각 숫자형 특징의 분포를 KDE 또는 히스토그램으로 그린다.

    Args:
        data (DataFrame): 시각화할 데이터.
        xnames (list|None): 대상 컬럼 목록(None이면 전 컬럼).
        hue (str|None): 클래스 컬럼.
        type (str): 'kde' | 'hist' | 'histkde'.
        bins (int|sequence|None): 히스토그램 구간.
        palette (str|None): 팔레트 이름.
        fill (bool): KDE 채움 여부.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.

    Returns:
        None
    """
    if xnames is None:
        xnames = data.columns

    for i, v in enumerate(xnames):
        # 종속변수이거나 숫자형이 아닌 경우는 제외
        if v == hue or data[v].dtype not in [
            "int",
            "int32",
            "int64",
            "float",
            "float32",
            "float64",
        ]:
            continue

        if type == "kde":
            hs_kdeplot(
                df=data,
                xname=v,
                hue=hue,
                palette=palette,
                fill=fill,
                width=width,
                height=height,
                dpi=dpi,
                callback=callback,
            )
        elif type == "hist":
            hs_histplot(
                df=data,
                xname=v,
                hue=hue,
                bins=bins,
                kde=False,
                palette=palette,
                width=width,
                height=height,
                dpi=dpi,
                callback=callback,
            )
        elif type == "histkde":
            hs_histplot(
                df=data,
                xname=v,
                hue=hue,
                bins=bins,
                kde=True,
                palette=palette,
                width=width,
                height=height,
                dpi=dpi,
                callback=callback,
            )

hs_scatter_by_class

hs_scatter_by_class(
    data,
    group=None,
    hue=None,
    palette=None,
    outline=False,
    width=1280,
    height=720,
    dpi=200,
    callback=None,
)

클래스별로 특징 쌍을 산점도 또는 볼록 껍질로 시각화한다.

Parameters:

Name Type Description Default
data DataFrame

시각화할 데이터.

required
group list | None

[[x, y], ...] 형태의 축 쌍 목록(None이면 자동 생성).

None
hue str | None

클래스 컬럼.

None
palette str | None

팔레트 이름.

None
outline bool

볼록 껍질을 표시할지 여부.

False
width int

캔버스 가로 픽셀.

1280
height int

캔버스 세로 픽셀.

720
dpi int

그림 크기 및 해상도.

200
callback Callable | None

Axes 후처리 콜백.

None

Returns:

Type Description
None

None

Source code in hossam/plot.py
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
def hs_scatter_by_class(
    data: DataFrame,
    group: list = None,
    hue: str = None,
    palette: str = None,
    outline: bool = False,
    width: int = 1280,
    height: int = 720,
    dpi: int = 200,
    callback: any = None,
) -> None:
    """클래스별로 특징 쌍을 산점도 또는 볼록 껍질로 시각화한다.

    Args:
        data (DataFrame): 시각화할 데이터.
        group (list|None): [[x, y], ...] 형태의 축 쌍 목록(None이면 자동 생성).
        hue (str|None): 클래스 컬럼.
        palette (str|None): 팔레트 이름.
        outline (bool): 볼록 껍질을 표시할지 여부.
        width (int): 캔버스 가로 픽셀.
        height (int): 캔버스 세로 픽셀.
        dpi (int): 그림 크기 및 해상도.
        callback (Callable|None): Axes 후처리 콜백.

    Returns:
        None
    """

    if group is None:
        group = []

        xnames = data.columns

        for i, v in enumerate(xnames):
            j = (i + 1) % len(xnames)

            if (
                v == hue
                or xnames[j] == hue
                or data[v].dtype
                not in [
                    "int",
                    "int32",
                    "int64",
                    "float",
                    "float32",
                    "float64",
                ]
            ):
                continue

            group.append([v, xnames[j]])

    if outline:
        for i, v in enumerate(group):
            hs_convex_hull(data, v[0], v[1], hue, palette, width, height, dpi, callback)
    else:
        for i, v in enumerate(group):
            hs_scatterplot(data, v[0], v[1], hue, palette, width, height, dpi, callback)