[파이썬] matplotlib 쌍둥이 축 (`twinx`, `twiny`)

In data visualization, it is often useful to plot multiple sets of data on the same graph. Matplotlib, a popular Python library for creating static, animated, and interactive visualizations, provides a convenient way to do this using twin axes. The twinx and twiny functions allow you to create a second y-axis or x-axis, respectively, sharing the same x-axis or y-axis with the original one.

Why use twin axes?

Twin axes come in handy when you want to compare two variables with different scales on the same graph. For example, you may have two datasets that measure temperature and rainfall. Temperature is typically plotted on the y-axis, while rainfall is better suited for the x-axis. Using twin axes in this scenario allows you to visualize the relationship between temperature and rainfall in a single plot.

Using twinx and twiny in Matplotlib

To create a twin y-axis in Matplotlib, you can call the twinx function on an existing axes object. Similarly, to create a twin x-axis, you can use the twiny function. Here’s an example to illustrate the usage:

import matplotlib.pyplot as plt

# Create the original axes
fig, ax1 = plt.subplots()

# Plot the first dataset on the original axes
ax1.plot(x, y1, 'b-', label='Dataset 1')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y-axis 1')

# Create a twin y-axis
ax2 = ax1.twinx()

# Plot the second dataset on the twin axes
ax2.plot(x, y2, 'r--', label='Dataset 2')
ax2.set_ylabel('Y-axis 2')

# Display the legend for both datasets
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')

# Show the plot
plt.show()

In this example, we first create the original axes using the subplots function. We then plot the first dataset on the original axes (ax1). Next, we create a twin y-axis (ax2) using the twinx function. We plot the second dataset on the twin axes and set the ylabel accordingly. Finally, we display the legend for both datasets using the legend function and show the plot.

Conclusion

Using twin axes (twinx and twiny) in Matplotlib provides a powerful way to compare two variables with different scales in a single plot. This feature is particularly useful when visualizing datasets that have different units or ranges. Experiment with twin axes in your data visualizations to deliver more compelling and informative graphs.