728x90
오늘은 회사에서 스케일 차이가 많이 나는 수치형 데이터의 추이를 비교해 볼 일이 있었습니다.
한 개의 플롯에 두 개의 그래프(차트)를 그려 넣는 방법을 찾아보고 정리합니다.
matplotlib.axes.Axes.twinx
matplotlib에서 제공하는 twinx를 사용하면, 동일한 플롯 내에서 x축을 공유하는 또 다른 y축을 생성할 수 있습니다.
아래는 간단한 예제입니다.
이 예에서는 'y1'의 기본 y축으로 'ax1'을 사용하고 'y2'의 보조 y축으로 'ax2'를 사용합니다. twinx() 함수는 동일한 x축을 공유하는 두 번째 y축을 생성합니다. 각각의 y축에 있는 두 선 그래프를 구별하기 위해 서로 다른 색상과 레이블을 할당합니다.
import matplotlib.pyplot as plt
# Sample data for the line graphs
x = [1, 2, 3, 4, 5]
y1 = [3, 5, 2, 6, 4]
y2 = [1000, 2000, 1500, 2400, 1800]
# Create a new figure and axis objects
fig, ax1 = plt.subplots(figsize=(8, 6))
ax2 = ax1.twinx() # Create a second y-axis sharing the same x-axis
# Plot the first line graph on the first y-axis
ax1.plot(x, y1, label='Graph 1', color='blue')
ax1.set_ylabel('Y-axis 1', color='blue')
# Plot the second line graph on the second y-axis
ax2.plot(x, y2, label='Graph 2', color='green')
ax2.set_ylabel('Y-axis 2', color='green')
# Set the title and labels for the graph
ax1.set_title('Two Line Graphs with Different Scales')
ax1.set_xlabel('X-axis')
# Display the legends
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
# Display the plot
plt.show()
Output:
728x90
'데이터분석과 AI > 데이터분석과 AI 문법(Python)' 카테고리의 다른 글
pd.describe() 사용법 (0) | 2023.08.16 |
---|---|
로그와 지수 함수 - np.log(), np.exp() (0) | 2023.07.15 |
수치형 데이터를 범주형으로 만드는 비닝(Binning)의 세 가지 방법 feat. Xverse (0) | 2023.07.06 |
cross_val_score 할 때 scoring에 입력 가능한 파라미터 (0) | 2023.07.02 |
데이터분석 초보자가 자주하는 실수- 정확도, 정밀도, 재현율, F1-score 까지 모든 성능지표가 1인 경우 (0) | 2023.06.30 |
댓글