본문 바로가기
Python_Wiki/Python_Library

matplotlib: 꺾은선 그래프 line chart(fill_between)

by yj-data 2025. 6. 5.
  • .fill_between()
  • 속 안을 채운 그래프는 꺾은선 그래프를 그리고 채우는 것이 아니라 애초에 채운 그래프를 그리게 됨

속 안을 채운 그래프의 예시

  • attributes
plt.fill_between(         # x축을 기준으로 그래프 영역을 채우는 함수
  x=df_unstack[1].index,  # x value
  y1=0, y2=df_unstack[1], # 채우기 시작 값, 끝 값, 두 값 사이가 색으로 채워짐
  color=[pie_color[2]],   
  alpha=0.9,              # 투명도
  label = '1'             
)

#.fill_betweenx() : y축을 기준으로 그래프 영역을 채우는 함수

 

 

example: step by step

 

#data
dict_data2 = {
    'a':[1,2,1,1,1,1,1,2,2,1,1,1,2,2], 
    'b':[2021,2022,2024,2023,2022,2023,2024,2022,2024,2024,2021,2024,2023,2021]
}
df2 = pd.DataFrame(dict_data2)
df_unstack = df2.groupby('b')['a'].value_counts().unstack()
df_unstack

plt.figure(figsize=(15,5))

plt.fill_between(x=df_unstack[1].index, y1=0, y2=df_unstack[1], color=[pie_color[2]], alpha=0.9, label = '1')
plt.fill_between(x=df_unstack[2].index, y1=0, y2=df_unstack[2], color=[pie_color[3]], alpha=0.9, label = '2')

plt.suptitle('The Title', fontfamily='serif', fontsize=14, fontweight='bold')
plt.title('The Second Title', fontfamily = 'sans-serif', fontsize=12)

plt.legend()

plt.show()

 

#changing the ticks

plt.figure(figsize=(15,5))

plt.fill_between(x=df_unstack[1].index, y1=0, y2=df_unstack[1], color=[pie_color[2]], alpha=0.9, label = '1')
plt.fill_between(x=df_unstack[2].index, y1=0, y2=df_unstack[2], color=[pie_color[3]], alpha=0.9, label = '2')

plt.suptitle('The Title', fontfamily='serif', fontsize=14, fontweight='bold')
plt.title('The Second Title', fontfamily = 'sans-serif', fontsize=12)

plt.xticks([2021, 2022, 2023, 2024],
           ['January', 'February', 'March', 'April'])
plt.legend()

plt.show()