IT TIP

PANDAS는 여러 Y 축을 플롯합니다.

itqueen 2021. 1. 7. 20:15
반응형

PANDAS는 여러 Y 축을 플롯합니다.


팬더가 보조 Y 축을 지원한다는 것을 알고 있지만, 플롯에 3 차 Y 축을 배치하는 방법을 아는 사람이 있는지 궁금합니다 ... 현재 numpy + pyplot으로 이것을 달성하고 있지만 큰 데이터 세트에서는 느립니다.

이것은 쉽게 비교할 수 있도록 동일한 그래프에 개별 단위를 사용하여 다른 측정 값을 표시하는 것입니다 (예 : 상대 습도 / 온도 / 및 전기 전도도).

pandas너무 많은 일 없이도 이것이 가능한지 아는 사람이 있다면 정말 궁금합니다 .

[편집] 나는 (너무 많은 오버 헤드없이) 이것을 할 수있는 방법이 있다는 것을 의심한다. 그러나 나는 틀린 것으로 증명되기를 바란다. 이것은 matplotlib의 한계일지도 모른다.


나는 이것이 효과가 있다고 생각한다.

import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
df = DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'])

fig, ax = plt.subplots()
ax3 = ax.twinx()
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.15))
ax3.set_frame_on(True)
ax3.patch.set_visible(False)
fig.subplots_adjust(right=0.7)

df.A.plot(ax=ax, style='b-')
# same ax as above since it's automatically added on the right
df.B.plot(ax=ax, style='r-', secondary_y=True)
df.C.plot(ax=ax3, style='g-')

# add legend --> take advantage of pandas providing us access
# to the line associated with the right part of the axis
ax3.legend([ax.get_lines()[0], ax.right_ax.get_lines()[0], ax3.get_lines()[0]],\
           ['A','B','C'], bbox_to_anchor=(1.5, 0.5))

산출:

산출


다음이없는 더 간단한 솔루션 plt:

ax1 = df1.plot()

ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
df2.plot(ax=ax2)

ax3 = ax1.twinx()
ax3.spines['right'].set_position(('axes', 1.1))
df3.plot(ax=ax3)

....

이를 달성하기 위해 기능 사용 :

def plot_multi(data, cols=None, spacing=.1, **kwargs):

    from pandas import plotting

    # Get default color style from pandas - can be changed to any other color list
    if cols is None: cols = data.columns
    if len(cols) == 0: return
    colors = getattr(getattr(plotting, '_matplotlib').style, '_get_standard_colors')(num_colors=len(cols))

    # First axis
    ax = data.loc[:, cols[0]].plot(label=cols[0], color=colors[0], **kwargs)
    ax.set_ylabel(ylabel=cols[0])
    lines, labels = ax.get_legend_handles_labels()

    for n in range(1, len(cols)):
        # Multiple y-axes
        ax_new = ax.twinx()
        ax_new.spines['right'].set_position(('axes', 1 + spacing * (n - 1)))
        data.loc[:, cols[n]].plot(ax=ax_new, label=cols[n], color=colors[n % len(colors)])
        ax_new.set_ylabel(ylabel=cols[n])

        # Proper legend position
        line, label = ax_new.get_legend_handles_labels()
        lines += line
        labels += label

    ax.legend(lines, labels, loc=0)
    return ax

예:

from random import randrange

data = pd.DataFrame(dict(
    s1=[randrange(-1000, 1000) for _ in range(100)],
    s2=[randrange(-100, 100) for _ in range(100)],
    s3=[randrange(-10, 10) for _ in range(100)],
))

plot_multi(data.cumsum(), figsize=(10, 5))

산출:

다중 Y 축

참조 URL : https://stackoverflow.com/questions/11640243/pandas-plot-multiple-y-axes

반응형