본문 바로가기
데이터 사이언스

for loop과 fig, ax 사용하여 그림 그리기

by 빛나는존재 2022. 7. 23.
import pandas as pd
import matplotlib.pyplot as plt

df={'channel': ['a', 'a', 'a', 'a','b','b','b','b'],
        'x': [1, 2, 3, 4,5,6,7,8],
        'y1':[10,20,30,40,50,60,70,80],
        'y2':[20,40,60,80, 100, 120, 140, 160],
        'y3':[30,60,90,120, 160, 180, 190, 200]
        }

df=pd.DataFrame(df)

channel_list = df.channel.unique()

nrow=len(df.channel.unique())
ncol=2
fig, ax = plt.subplots(nrow,ncol,figsize=(10,15))


for a,channel in enumerate(channel_list):

    ax[a,0].plot(df.loc[df.channel==channel,'x'], df.loc[df.channel==channel,'y1'], color='g', label='raw rfu')
    ax[a,0].legend()
    ax[a,0].set_title('title = {}'.format(channel))

    #overlaying y2 and y3 into a single plot
    ax[a,1].plot(df.loc[df.channel==channel,'x'], df.loc[df.channel==channel,'y2'], color='r', label='y2')
    ax[a,1].plot(df.loc[df.channel==channel,'x'], df.loc[df.channel==channel,'y3'], color='b', label='y3')
    ax[a,1].legend()

plt.show()
plt.clf()
 
반응형