본문 바로가기
데이터분석과 AI/데이터분석과 AI 문법(Python)

동일한 플롯에 스케일이 다른 그래프를 그리고 싶을 때 twinx()

by 우공80 2023. 7. 13.
728x90

twinx()

오늘은 회사에서 스케일 차이가 많이 나는 수치형 데이터의 추이를 비교해 볼 일이 있었습니다.

한 개의 플롯에 두 개의 그래프(차트)를 그려 넣는 방법을 찾아보고 정리합니다. 

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

댓글