Skip to content

zerohertzLib.plot

Plot

다양한 변수들을 최대한 지정하지 않고 사용할 수 있는 시각화 함수들

Modules:

Name Description
bar_chart
config
pie
plot
scatter
table
util

Functions:

Name Description
barh

Dictionary로 입력받은 data를 세로 bar chart로 시각화

barv

Dictionary로 입력받은 data를 가로 bar chart로 시각화

candle

OHLCV (Open, High, Low, Close, Volume) data에 따른 candle chart

color

색 추출 function

figure

Graph 생성을 위한 function

font

plot submodule 내 사용될 font 및 크기 설정

hist

Dictionary로 입력받은 data를 histogram으로 시각화

savefig

Graph 저장 function

subplot

Subplot 생성을 위한 function

FONT_PATH module-attribute

FONT_PATH = join(dirname(__file__), 'fonts')

__all__ module-attribute

__all__ = ['barv', 'barh', 'hist', 'plot', 'pie', 'scatter', 'color', 'table', 'savefig', 'figure', 'candle', 'font', 'subplot']

barh

barh(data: dict[str, Any], xlab: str | None = None, ylab: str | None = None, xlim: list[int | float] | None = None, ylim: list[int | float] | None = None, title: str = 'tmp', colors: str | list | None = None, figsize: tuple[int, int] = (10, 15), rot: int = 0, dim: str | None = None, dimsize: float = 10, sign: int = 1, dpi: int = 300) -> str | None

Dictionary로 입력받은 data를 세로 bar chart로 시각화

Parameters:

Name Type Description Default
data dict[str, Any]

입력 data

required
xlab str | None

Graph에 출력될 X축 label

None
ylab str | None

Graph에 출력될 Y축 label

None
xlim list[int | float] | None

Graph에 출력될 X축 limit

None
ylim list[int | float] | None

Graph에 출력될 Y축 limit

None
title str

Graph에 표시될 제목 및 file 이름

'tmp'
colors str | list | None

각 요소의 색

None
figsize tuple[int, int]

Graph의 가로, 세로 길이

(10, 15)
rot int

X축의 눈금 회전 각도

0
dim str | None

각 bar 상단에 표시될 값의 단위 (%: percentage)

None
dimsize float

각 bar 상단에 표시될 값의 크기

10
sign int

각 bar 상단에 표시될 값의 유효숫자

1
dpi int

Graph 저장 시 DPI (Dots Per Inch)

300

Returns:

Type Description
str | None

저장된 graph의 절대 경로

Examples:

>>> data = {"Terran": 27, "Zerg": 40, "Protoss": -30}
>>> zz.plot.barh(data, xlab="Population", ylab="Races", title="Star Craft", dim="")
>>> data = {"yticks": ["Terran", "Zerg", "Protoss"], "Type A": [4, 5, 6], "Type B": [4, 3, 2], "Type C": [8, 5, 12], "Type D": [6, 3, 2]}
>>> zz.plot.barh(data, xlab="Time [Sec]", ylab="Races", title="Star Craft", dim="%", sign=2)

Horizontal bar chart example

Source code in zerohertzLib/plot/bar_chart.py
def barh(
    data: dict[str, Any],
    xlab: str | None = None,
    ylab: str | None = None,
    xlim: list[int | float] | None = None,
    ylim: list[int | float] | None = None,
    title: str = "tmp",
    colors: str | list | None = None,
    figsize: tuple[int, int] = (10, 15),
    rot: int = 0,
    dim: str | None = None,
    dimsize: float = 10,
    sign: int = 1,
    dpi: int = 300,
) -> str | None:
    """Dictionary로 입력받은 data를 세로 bar chart로 시각화

    Args:
        data: 입력 data
        xlab: Graph에 출력될 X축 label
        ylab: Graph에 출력될 Y축 label
        xlim: Graph에 출력될 X축 limit
        ylim: Graph에 출력될 Y축 limit
        title: Graph에 표시될 제목 및 file 이름
        colors: 각 요소의 색
        figsize: Graph의 가로, 세로 길이
        rot: X축의 눈금 회전 각도
        dim: 각 bar 상단에 표시될 값의 단위 (`%`: percentage)
        dimsize: 각 bar 상단에 표시될 값의 크기
        sign: 각 bar 상단에 표시될 값의 유효숫자
        dpi: Graph 저장 시 DPI (Dots Per Inch)

    Returns:
        저장된 graph의 절대 경로

    Examples:
        >>> data = {"Terran": 27, "Zerg": 40, "Protoss": -30}
        >>> zz.plot.barh(data, xlab="Population", ylab="Races", title="Star Craft", dim="")
        >>> data = {"yticks": ["Terran", "Zerg", "Protoss"], "Type A": [4, 5, 6], "Type B": [4, 3, 2], "Type C": [8, 5, 12], "Type D": [6, 3, 2]}
        >>> zz.plot.barh(data, xlab="Time [Sec]", ylab="Races", title="Star Craft", dim="%", sign=2)

        ![Horizontal bar chart example](../../../assets/plot/barh.png){ width="450" }
    """
    colors = _color(data, colors)
    if config.SAVE:
        plt.figure(figsize=figsize)
    if isinstance(list(data.values())[-1], list):
        data = data.copy()
        try:
            yticks = data.pop("yticks")
        except KeyError:
            yticks = list(range(len(list(data.values())[-1])))
        left = np.array([0 for _ in range(len(list(data.values())[-1]))])
        for i, (key, value) in enumerate(data.items()):
            bars = plt.barh(
                yticks, value, color=colors[i], zorder=2, label=key, left=left
            )
            left += np.array(value)
        plt.legend()
        plt.xlim([0, 1.1 * left.max()])
        if dim is None:
            pass
        elif dim == "%":
            maximum = left.max()
            total = left.sum()
            for bar_, left_ in zip(bars, left):
                percentage = (left_ / total) * 100
                plt.text(
                    left_ + maximum * 0.01,
                    bar_.get_y() + bar_.get_height() / 2,
                    f"{percentage:.{sign}f}%",
                    ha="left",
                    va="center",
                    rotation=270,
                    fontsize=dimsize,
                )
        else:
            maximum = left.max()
            for bar_, left_ in zip(bars, left):
                plt.text(
                    left_ + maximum * 0.01,
                    bar_.get_y() + bar_.get_height() / 2,
                    f"{left_:.{sign}f}{dim}",
                    ha="left",
                    va="center",
                    rotation=270,
                    fontsize=dimsize,
                )
    else:
        bars = plt.barh(list(data.keys()), list(data.values()), color=colors, zorder=2)
        if min(data.values()) > 0:
            plt.xlim([0, 1.1 * max(list(data.values()))])
        if dim is None:
            pass
        elif dim == "%":
            maximum = max(list(data.values()))
            total = sum(list(data.values()))
            for bar_ in bars:
                width = bar_.get_width()
                percentage = (width / total) * 100
                plt.text(
                    width + maximum * 0.01,
                    bar_.get_y() + bar_.get_height() / 2,
                    f"{percentage:.{sign}f}%",
                    ha="left",
                    va="center",
                    rotation=270,
                    fontsize=dimsize,
                )
        else:
            maximum = max(list(data.values()))
            minimum = min(list(data.values()))
            for bar_ in bars:
                width = position = bar_.get_width()
                if width < 0:
                    position -= (maximum - minimum) * 0.01
                    ha = "right"
                else:
                    position += (maximum - minimum) * 0.01
                    ha = "left"
                plt.text(
                    position,
                    bar_.get_y() + bar_.get_height() / 2,
                    f"{width:.{sign}f}{dim}",
                    ha=ha,
                    va="center",
                    rotation=270,
                    fontsize=dimsize,
                )
    plt.grid(zorder=0)
    if xlab:
        plt.xlabel(xlab)
    if ylab:
        plt.ylabel(ylab)
    if xlim:
        plt.xlim(xlim)
    if ylim:
        plt.ylim(ylim)
    plt.yticks(rotation=rot)
    plt.title(title, fontsize=25)
    if config.SAVE:
        return savefig(title, dpi)
    return None

barv

barv(data: dict[str, Any], xlab: str | None = None, ylab: str | None = None, xlim: list[int | float] | None = None, ylim: list[int | float] | None = None, title: str = 'tmp', colors: str | list | None = None, figsize: tuple[int, int] = (15, 10), rot: int = 0, dim: str | None = None, dimsize: float = 10, sign: int = 1, dpi: int = 300) -> str | None

Dictionary로 입력받은 data를 가로 bar chart로 시각화

Parameters:

Name Type Description Default
data dict[str, Any]

입력 data

required
xlab str | None

Graph에 출력될 X축 label

None
ylab str | None

Graph에 출력될 Y축 label

None
xlim list[int | float] | None

Graph에 출력될 X축 limit

None
ylim list[int | float] | None

Graph에 출력될 Y축 limit

None
title str

Graph에 표시될 제목 및 file 이름

'tmp'
colors str | list | None

각 요소의 색

None
figsize tuple[int, int]

Graph의 가로, 세로 길이

(15, 10)
rot int

X축의 눈금 회전 각도

0
dim str | None

각 bar 상단에 표시될 값의 단위 (%: percentage)

None
dimsize float

각 bar 상단에 표시될 값의 크기

10
sign int

각 bar 상단에 표시될 값의 유효숫자

1
dpi int

Graph 저장 시 DPI (Dots Per Inch)

300

Returns:

Type Description
str | None

저장된 graph의 절대 경로

Examples:

>>> data = {"Terran": 27, "Zerg": 40, "Protoss": -30}
>>> zz.plot.barv(data, xlab="Races", ylab="Population", title="Star Craft", dim="")
>>> data = {"xticks": ["Terran", "Zerg", "Protoss"], "Type A": [4, 5, 6], "Type B": [4, 3, 2], "Type C": [8, 5, 12], "Type D": [6, 3, 2]}
>>> zz.plot.barv(data, xlab="Races", ylab="Time [sec]", title="Star Craft", dim="%", sign=2)

Vertical bar chart example

Source code in zerohertzLib/plot/bar_chart.py
def barv(
    data: dict[str, Any],
    xlab: str | None = None,
    ylab: str | None = None,
    xlim: list[int | float] | None = None,
    ylim: list[int | float] | None = None,
    title: str = "tmp",
    colors: str | list | None = None,
    figsize: tuple[int, int] = (15, 10),
    rot: int = 0,
    dim: str | None = None,
    dimsize: float = 10,
    sign: int = 1,
    dpi: int = 300,
) -> str | None:
    """Dictionary로 입력받은 data를 가로 bar chart로 시각화

    Args:
        data: 입력 data
        xlab: Graph에 출력될 X축 label
        ylab: Graph에 출력될 Y축 label
        xlim: Graph에 출력될 X축 limit
        ylim: Graph에 출력될 Y축 limit
        title: Graph에 표시될 제목 및 file 이름
        colors: 각 요소의 색
        figsize: Graph의 가로, 세로 길이
        rot: X축의 눈금 회전 각도
        dim: 각 bar 상단에 표시될 값의 단위 (`%`: percentage)
        dimsize: 각 bar 상단에 표시될 값의 크기
        sign: 각 bar 상단에 표시될 값의 유효숫자
        dpi: Graph 저장 시 DPI (Dots Per Inch)

    Returns:
        저장된 graph의 절대 경로

    Examples:
        >>> data = {"Terran": 27, "Zerg": 40, "Protoss": -30}
        >>> zz.plot.barv(data, xlab="Races", ylab="Population", title="Star Craft", dim="")
        >>> data = {"xticks": ["Terran", "Zerg", "Protoss"], "Type A": [4, 5, 6], "Type B": [4, 3, 2], "Type C": [8, 5, 12], "Type D": [6, 3, 2]}
        >>> zz.plot.barv(data, xlab="Races", ylab="Time [sec]", title="Star Craft", dim="%", sign=2)

        ![Vertical bar chart example](../../../assets/plot/barv.png){ width="600" }
    """
    colors = _color(data, colors)
    if config.SAVE:
        plt.figure(figsize=figsize)
    if isinstance(list(data.values())[-1], list):
        data = data.copy()
        try:
            xticks = data.pop("xticks")
        except KeyError:
            xticks = list(range(len(list(data.values())[-1])))
        bottom = np.array([0 for _ in range(len(list(data.values())[-1]))])
        for i, (key, value) in enumerate(data.items()):
            bars = plt.bar(
                xticks, value, color=colors[i], zorder=2, label=key, bottom=bottom
            )
            bottom += np.array(value)
        plt.legend()
        plt.ylim([0, 1.1 * bottom.max()])
        if dim is None:
            pass
        elif dim == "%":
            maximum = bottom.max()
            total = bottom.sum()
            for bar_, bot in zip(bars, bottom):
                percentage = (bot / total) * 100
                plt.text(
                    bar_.get_x() + bar_.get_width() / 2,
                    bot + maximum * 0.01,
                    f"{percentage:.{sign}f}%",
                    ha="center",
                    va="bottom",
                    fontsize=dimsize,
                )
        else:
            maximum = bottom.max()
            for bar_, bot in zip(bars, bottom):
                plt.text(
                    bar_.get_x() + bar_.get_width() / 2,
                    bot + maximum * 0.01,
                    f"{bot:.{sign}f}{dim}",
                    ha="center",
                    va="bottom",
                    fontsize=dimsize,
                )
    else:
        bars = plt.bar(
            data.keys(),
            data.values(),
            color=colors,
            zorder=2,
        )
        if min(data.values()) > 0:
            plt.ylim([0, 1.1 * max(list(data.values()))])
        if dim is None:
            pass
        elif dim == "%":
            maximum = max(list(data.values()))
            total = sum(list(data.values()))
            for bar_ in bars:
                height = bar_.get_height()
                percentage = (height / total) * 100
                plt.text(
                    bar_.get_x() + bar_.get_width() / 2,
                    height + maximum * 0.01,
                    f"{percentage:.{sign}f}%",
                    ha="center",
                    va="bottom",
                    fontsize=dimsize,
                )
        else:
            maximum = max(list(data.values()))
            minimum = min(list(data.values()))
            for bar_ in bars:
                height = position = bar_.get_height()
                if height < 0:
                    position -= (maximum - minimum) * 0.01
                    va = "top"
                else:
                    position += (maximum - minimum) * 0.01
                    va = "bottom"
                plt.text(
                    bar_.get_x() + bar_.get_width() / 2,
                    position,
                    f"{height:.{sign}f}{dim}",
                    ha="center",
                    va=va,
                    fontsize=dimsize,
                )
    plt.grid(zorder=0)
    if xlab:
        plt.xlabel(xlab)
    if ylab:
        plt.ylabel(ylab)
    if xlim:
        plt.xlim(xlim)
    if ylim:
        plt.ylim(ylim)
    plt.xticks(rotation=rot)
    plt.title(title, fontsize=25)
    if config.SAVE:
        return savefig(title, dpi)
    return None

candle

candle(data: DataFrame, title: str = 'tmp', figsize: tuple[int, int] = (18, 10), signals: dict[str, Any] | None = None, threshold: int | tuple[int, int] = 1, dpi: int = 300) -> str | None

OHLCV (Open, High, Low, Close, Volume) data에 따른 candle chart

Note
  • 적색: 매수
  • 청색: 매도
  • 실선: Backtest 시 signal이 존재하는 매수, 매도
  • 파선: Backtest 시 사용하지 않은 signal의 매수, 매도
  • 일점쇄선: Backtest logic에 의한 매수, 매도

Parameters:

Name Type Description Default
data DataFrame

OHLCV (Open, High, Low, Close, Volume) data

required
title str

Graph에 표시될 제목 및 file 이름

'tmp'
figsize tuple[int, int]

Graph의 가로, 세로 길이

(18, 10)
signals dict[str, Any] | None

추가적으로 plot할 data

None
threshold int | tuple[int, int]

매수, 매도를 결정할 signals 경계값

1
dpi int

Graph 저장 시 DPI (Dots Per Inch)

300

Returns:

Type Description
str | None

저장된 graph의 절대 경로

Examples:

>>> zz.plot.candle(data, title)
>>> signals = zz.quant.macd(data)
>>> zz.plot.candle(data, "MACD", signals=signals)

Candle chart example

Source code in zerohertzLib/plot/plot.py
def candle(
    data: pd.DataFrame,
    title: str = "tmp",
    figsize: tuple[int, int] = (18, 10),
    signals: dict[str, Any] | None = None,
    threshold: int | tuple[int, int] = 1,
    dpi: int = 300,
) -> str | None:
    """OHLCV (Open, High, Low, Close, Volume) data에 따른 candle chart

    Note:
        - 적색: 매수
        - 청색: 매도
        - 실선: Backtest 시 signal이 존재하는 매수, 매도
        - 파선: Backtest 시 사용하지 않은 signal의 매수, 매도
        - 일점쇄선: Backtest logic에 의한 매수, 매도

    Args:
        data: OHLCV (Open, High, Low, Close, Volume) data
        title: Graph에 표시될 제목 및 file 이름
        figsize: Graph의 가로, 세로 길이
        signals: 추가적으로 plot할 data
        threshold: 매수, 매도를 결정할 `signals` 경계값
        dpi: Graph 저장 시 DPI (Dots Per Inch)

    Returns:
        저장된 graph의 절대 경로

    Examples:
        >>> zz.plot.candle(data, title)
        >>> signals = zz.quant.macd(data)
        >>> zz.plot.candle(data, "MACD", signals=signals)

        ![Candle chart example](../../../assets/plot/candle.png){ width="600" }
    """
    if not isinstance(threshold, int):
        threshold_sell, threshold_buy = threshold
    else:
        threshold_sell, threshold_buy = -threshold, threshold
    marketcolors = mpf.make_marketcolors(
        up="red",
        down="blue",
        edge="black",
        volume={"up": "red", "down": "blue"},
        inherit=False,
    )
    marketcolors["vcedge"] = {"up": "#000000", "down": "#000000"}
    style = mpf.make_mpf_style(
        marketcolors=marketcolors,
        mavcolors=color(3),
        facecolor="white",
        edgecolor="black",
        figcolor="white",
        gridcolor="gray",
        gridstyle="-",
        rc={
            "font.size": plt.rcParams["font.size"],
            "font.family": plt.rcParams["font.family"],
            "figure.titlesize": 35,
        },
    )
    # bands = _bollinger_bands(data)
    # bollinger = mpf.make_addplot(bands[["lower_band", "upper_band"]], type="line")
    _, axlist = mpf.plot(
        data,
        type="candle",
        mav=(5, 20, 60, 120),
        volume=True,
        figsize=figsize,
        title=title,
        style=style,
        returnfig=True,
        # addplot=bollinger,
    )
    if signals is not None:
        new_axis = axlist[0].twinx()
        xdata = axlist[0].get_lines()[0].get_xdata()
        buy_idx_signal = []
        sell_idx_signal = []
        buy_idx_backtest = []
        sell_idx_backtest = []
        buy_idx_logic = []
        sell_idx_logic = []
        if "logic" not in signals.columns:
            signals["logic"] = 0
        for idx, (pos_signals, pos_logic) in enumerate(
            zip(signals["signals"], signals["logic"])
        ):
            if pos_logic == 1:
                buy_idx_backtest.append(idx)
            elif pos_logic == -1:
                sell_idx_backtest.append(idx)
            elif pos_logic == 2:
                buy_idx_logic.append(idx)
            elif pos_logic == -2:
                sell_idx_logic.append(idx)
            elif pos_signals >= threshold_buy:
                buy_idx_signal.append(idx)
            elif pos_signals <= threshold_sell:
                sell_idx_signal.append(idx)
        for i in buy_idx_signal:
            new_axis.axvline(
                x=xdata[i], color="red", linestyle="--", linewidth=2, alpha=0.3
            )
        for i in sell_idx_signal:
            new_axis.axvline(
                x=xdata[i], color="blue", linestyle="--", linewidth=2, alpha=0.3
            )
        for i in buy_idx_backtest:
            new_axis.axvline(
                x=xdata[i], color="red", linestyle="-", linewidth=2, alpha=0.3
            )
        for i in sell_idx_backtest:
            new_axis.axvline(
                x=xdata[i], color="blue", linestyle="-", linewidth=2, alpha=0.3
            )
        for i in buy_idx_logic:
            new_axis.axvline(
                x=xdata[i], color=(1, 0.2, 0), linestyle="-.", linewidth=2, alpha=0.3
            )
        for i in sell_idx_logic:
            new_axis.axvline(
                x=xdata[i], color=(0, 0.2, 1), linestyle="-.", linewidth=2, alpha=0.3
            )
        colors = color(len(signals.columns), palette="Set1")
        if len(signals.columns) > 1:
            for idx, col in enumerate(signals.columns[:-2]):
                new_axis.plot(
                    xdata,
                    signals[col],
                    color=colors[idx],
                    linewidth=3,
                    alpha=0.5,
                    label=_method2str(col),
                )
            plt.legend()
        new_axis.set_yticks([])
        new_axis = axlist[0].twinx()
        new_axis.plot(
            xdata,
            signals["signals"],
            color="black",
            linewidth=1,
        )
        new_axis.set_yticks([])
    if config.SAVE:
        return savefig(title, dpi)
    return None

color

color(cnt: int = 1, rand: bool = False, uint8: bool = False, palette: str = 'husl') -> tuple[float, float, float] | list[int] | list[tuple[float, float, float]] | list[list[int]]

색 추출 function

Parameters:

Name Type Description Default
cnt int

추출할 색의 수

1
rand bool

Random 추출 여부

False
uint8 bool

출력 색상의 type

False
palette str

추출할 색들의 palette

'husl'

Returns:

Type Description
tuple[float, float, float] | list[int] | list[tuple[float, float, float]] | list[list[int]]

단일 색 또는 list로 구성된 여러 색

Examples:

>>> zz.plot.color()
(0.9710194877714075, 0.4645444048369612, 0.21958695134807432)
>>> zz.plot.color(4)
[(0.9677975592919913, 0.44127456009157356, 0.5358103155058701), (0.5920891529639701, 0.6418467016378244, 0.1935069134991043), (0.21044753832183283, 0.6773105080456748, 0.6433941168468681), (0.6423044349219739, 0.5497680051256467, 0.9582651433656727)]
>>> zz.plot.color(4, True)
[(0.22420518847992715, 0.6551391052055489, 0.8272616286387289), (0.9677975592919913, 0.44127456009157356, 0.5358103155058701), (0.21125140522513897, 0.6760830215342485, 0.6556099802889619), (0.9590000285927794, 0.36894286394742526, 0.9138608732554839)]
>>> zz.plot.color(uint8=True)
[53, 172, 167]
>>> zz.plot.color(4, uint8=True)
[[246, 112, 136], [150, 163, 49], [53, 172, 164], [163, 140, 244]]
>>> zz.plot.color(4, True, True)
[[247, 117, 79], [73, 160, 244], [54, 171, 176], [110, 172, 49]]
Source code in zerohertzLib/plot/util.py
def color(
    cnt: int = 1,
    rand: bool = False,
    uint8: bool = False,
    palette: str = "husl",
) -> (
    tuple[float, float, float]
    | list[int]
    | list[tuple[float, float, float]]
    | list[list[int]]
):
    """색 추출 function

    Args:
        cnt: 추출할 색의 수
        rand: Random 추출 여부
        uint8: 출력 색상의 type
        palette: 추출할 색들의 palette

    Returns:
        단일 색 또는 list로 구성된 여러 색

    Examples:
        >>> zz.plot.color()
        (0.9710194877714075, 0.4645444048369612, 0.21958695134807432)
        >>> zz.plot.color(4)
        [(0.9677975592919913, 0.44127456009157356, 0.5358103155058701), (0.5920891529639701, 0.6418467016378244, 0.1935069134991043), (0.21044753832183283, 0.6773105080456748, 0.6433941168468681), (0.6423044349219739, 0.5497680051256467, 0.9582651433656727)]
        >>> zz.plot.color(4, True)
        [(0.22420518847992715, 0.6551391052055489, 0.8272616286387289), (0.9677975592919913, 0.44127456009157356, 0.5358103155058701), (0.21125140522513897, 0.6760830215342485, 0.6556099802889619), (0.9590000285927794, 0.36894286394742526, 0.9138608732554839)]
        >>> zz.plot.color(uint8=True)
        [53, 172, 167]
        >>> zz.plot.color(4, uint8=True)
        [[246, 112, 136], [150, 163, 49], [53, 172, 164], [163, 140, 244]]
        >>> zz.plot.color(4, True, True)
        [[247, 117, 79], [73, 160, 244], [54, 171, 176], [110, 172, 49]]
    """
    if cnt == 1:
        if uint8:
            return [
                int(i * 255)
                for i in random.choice(sns.color_palette(palette, n_colors=100))
            ]
        return random.choice(sns.color_palette(palette, n_colors=100))
    if rand:
        if uint8:
            return [
                [int(j * 255) for j in i]
                for i in random.choices(sns.color_palette(palette, n_colors=100), k=cnt)
            ]
        return random.choices(sns.color_palette(palette, n_colors=100), k=cnt)
    if uint8:
        return [
            [int(j * 255) for j in i] for i in sns.color_palette(palette, n_colors=cnt)
        ]
    return sns.color_palette(palette, n_colors=cnt)

figure

figure(figsize: tuple[int, int] = (15, 10)) -> Figure

Graph 생성을 위한 function

Parameters:

Name Type Description Default
figsize tuple[int, int]

Graph의 가로, 세로 길이

(15, 10)

Returns:

Type Description
Figure

Graph window 생성

Examples:

>>> zz.plot.figure()
<Figure size 1500x1000 with 0 Axes>
>>> zz.plot.figure((20, 20))
<Figure size 2000x2000 with 0 Axes>
Source code in zerohertzLib/plot/util.py
def figure(figsize: tuple[int, int] = (15, 10)) -> Figure:
    """Graph 생성을 위한 function

    Args:
        figsize: Graph의 가로, 세로 길이

    Returns:
        Graph window 생성

    Examples:
        >>> zz.plot.figure()
        <Figure size 1500x1000 with 0 Axes>
        >>> zz.plot.figure((20, 20))
        <Figure size 2000x2000 with 0 Axes>
    """
    fig = plt.figure(figsize=figsize)
    config.SAVE = False
    return fig

font

font(kor: bool = False, size: int = 20) -> None

plot submodule 내 사용될 font 및 크기 설정

Parameters:

Name Type Description Default
kor bool

한국어 여부

False
size int

Font의 크기

20

Returns:

Type Description
None

plt.rcParams 을 통한 전역적 설정

Source code in zerohertzLib/plot/__init__.py
def font(kor: bool = False, size: int = 20) -> None:
    """`plot` submodule 내 사용될 font 및 크기 설정

    Args:
        kor: 한국어 여부
        size: Font의 크기

    Returns:
        `plt.rcParams` 을 통한 전역적 설정
    """
    plt.rcParams["font.size"] = size
    # font_path = os.path.join(os.path.dirname(__file__), "fonts")
    if kor:
        font_manager.fontManager.addfont(
            os.path.join(FONT_PATH, "NotoSerifKR-Medium.otf")
        )
        plt.rcParams["font.family"] = "Noto Serif KR"
    else:
        font_manager.fontManager.addfont(os.path.join(FONT_PATH, "times.ttf"))
        plt.rcParams["font.family"] = "Times New Roman"

hist

hist(data: dict[str, list[int | float]], xlab: str | None = None, ylab: str | None = None, xlim: list[int | float] | None = None, ylim: list[int | float] | None = None, title: str = 'tmp', colors: str | list | None = None, cnt: int = 30, ovp: bool = True, figsize: tuple[int, int] = (15, 10), dpi: int = 300) -> str | None

Dictionary로 입력받은 data를 histogram으로 시각화

Parameters:

Name Type Description Default
data dict[str, list[int | float]]

입력 data

required
xlab str | None

Graph에 출력될 X축 label

None
ylab str | None

Graph에 출력될 Y축 label

None
xlim list[int | float] | None

Graph에 출력될 X축 limit

None
ylim list[int | float] | None

Graph에 출력될 Y축 limit

None
title str

Graph에 표시될 제목 및 file 이름

'tmp'
colors str | list | None

각 요소의 색

None
cnt int

Bin의 개수

30
ovp bool

Class에 따른 histogram overlap 여부

True
figsize tuple[int, int]

Graph의 가로, 세로 길이

(15, 10)
dpi int

Graph 저장 시 DPI (Dots Per Inch)

300

Returns:

Type Description
str | None

저장된 graph의 절대 경로

Examples:

>>> data = {"Terran": list(np.random.rand(1000) * 10), "Zerg": list(np.random.rand(1000) * 10 + 1), "Protoss": list(np.random.rand(1000) * 10 + 2)}
>>> zz.plot.hist(data, xlab="Scores", ylab="Population", title="Star Craft")

Histogram example

Source code in zerohertzLib/plot/bar_chart.py
def hist(
    data: dict[str, list[int | float]],
    xlab: str | None = None,
    ylab: str | None = None,
    xlim: list[int | float] | None = None,
    ylim: list[int | float] | None = None,
    title: str = "tmp",
    colors: str | list | None = None,
    cnt: int = 30,
    ovp: bool = True,
    figsize: tuple[int, int] = (15, 10),
    dpi: int = 300,
) -> str | None:
    """Dictionary로 입력받은 data를 histogram으로 시각화

    Args:
        data: 입력 data
        xlab: Graph에 출력될 X축 label
        ylab: Graph에 출력될 Y축 label
        xlim: Graph에 출력될 X축 limit
        ylim: Graph에 출력될 Y축 limit
        title: Graph에 표시될 제목 및 file 이름
        colors: 각 요소의 색
        cnt: Bin의 개수
        ovp: Class에 따른 histogram overlap 여부
        figsize: Graph의 가로, 세로 길이
        dpi: Graph 저장 시 DPI (Dots Per Inch)

    Returns:
        저장된 graph의 절대 경로

    Examples:
        >>> data = {"Terran": list(np.random.rand(1000) * 10), "Zerg": list(np.random.rand(1000) * 10 + 1), "Protoss": list(np.random.rand(1000) * 10 + 2)}
        >>> zz.plot.hist(data, xlab="Scores", ylab="Population", title="Star Craft")

        ![Histogram example](../../../assets/plot/hist.png){ width="600" }
    """
    colors = _color(data, colors)
    minimum, maximum = sys.maxsize, -sys.maxsize
    for ydata in data.values():
        minimum = min(*ydata, minimum)
        maximum = max(*ydata, maximum)
    gap = max(0.01, (maximum - minimum) / cnt)
    bins = np.linspace(minimum - gap, maximum + gap, cnt)
    if config.SAVE:
        plt.figure(figsize=figsize)
    if ovp:
        for i, (key, value) in enumerate(data.items()):
            plt.hist(value, bins=bins, color=colors[i], label=key, alpha=0.7, zorder=2)
    else:
        plt.hist(
            list(data.values()),
            bins=bins,
            color=colors,
            label=list(data.keys()),
            alpha=1,
            zorder=2,
        )
    plt.grid(zorder=0)
    if xlab:
        plt.xlabel(xlab)
    if ylab:
        plt.ylabel(ylab)
    if xlim:
        plt.xlim(xlim)
    if ylim:
        plt.ylim(ylim)
    plt.title(title, fontsize=25)
    if len(data) > 1:
        plt.legend()
    if config.SAVE:
        return savefig(title, dpi)
    return None

savefig

savefig(title: str, dpi: int = 300) -> str

Graph 저장 function

Parameters:

Name Type Description Default
title str

Graph file 이름

required
dpi int

Graph 저장 시 DPI (Dots Per Inch)

300

Returns:

Type Description
str

저장된 graph의 절대 경로

Examples:

>>> zz.plot.savefig("Star Craft")
Source code in zerohertzLib/plot/util.py
def savefig(title: str, dpi: int = 300) -> str:
    """Graph 저장 function

    Args:
        title: Graph file 이름
        dpi: Graph 저장 시 DPI (Dots Per Inch)

    Returns:
        저장된 graph의 절대 경로

    Examples:
        >>> zz.plot.savefig("Star Craft")
    """
    title = title.lower().replace(" ", "_").replace("/", "-")
    plt.savefig(
        f"{title}.png",
        dpi=dpi,
        bbox_inches="tight",
    )
    plt.close("all")
    config.SAVE = True
    return os.path.abspath(f"{title}.png")

subplot

subplot(*args: Any, **kwargs: Any) -> Axes

Subplot 생성을 위한 function

Parameters:

Name Type Description Default
*args Any

matplotlib.pyplot.subplot의 위치 인수들

()
**kwargs Any

matplotlib.pyplot.subplot의 키워드 인수들

{}

Returns:

Type Description
Axes

Subplot axes 생성

Examples:

>>> zz.plot.subplot(nrows, ncols, index, **kwargs)
>>> zz.plot.subplot(2, 1, 1)
<Axes: >
Source code in zerohertzLib/plot/util.py
def subplot(*args: Any, **kwargs: Any) -> Axes:
    """Subplot 생성을 위한 function

    Args:
        *args: matplotlib.pyplot.subplot의 위치 인수들
        **kwargs: matplotlib.pyplot.subplot의 키워드 인수들

    Returns:
        Subplot axes 생성

    Examples:
        >>> zz.plot.subplot(nrows, ncols, index, **kwargs)
        >>> zz.plot.subplot(2, 1, 1)
        <Axes: >
    """
    return plt.subplot(*args, **kwargs)