[파이썬] matplotlib 축의 범위 및 비율 조절

Matplotlib is a popular Python library for creating visualizations. One important aspect of creating effective and informative plots is adjusting the range and ratio of the axes. In this blog post, we will explore how to control the range and ratio of axes in Matplotlib.

Adjusting Axis Range

Sometimes, the default range of the axes may not display the desired data range effectively. Matplotlib provides several methods to adjust the axis range, ensuring that the plot displays the required data appropriately.

xlim() and ylim()

The xlim() and ylim() functions can be used to set the x-axis and y-axis ranges, respectively. By specifying the minimum and maximum values, you can focus on a specific range of the data.

import matplotlib.pyplot as plt

plt.plot(x, y)  # Assuming x and y are the data points
plt.xlim(min_x, max_x)
plt.ylim(min_y, max_y)
plt.show()

axis()

The axis() function provides a convenient way to set the x-axis and y-axis ranges simultaneously. By passing in a list [xmin, xmax, ymin, ymax], you can specify the range of both axes at once.

import matplotlib.pyplot as plt

plt.plot(x, y)  # Assuming x and y are the data points
plt.axis([min_x, max_x, min_y, max_y])
plt.show()

Adjusting Axis Ratio

In some cases, it may be necessary to adjust the ratio of the axes to accurately represent the underlying data. Matplotlib allows you to modify the aspect ratio of the plot using the aspect parameter.

set_aspect()

The set_aspect() function can be used to modify the aspect ratio of the plot. The parameter aspect accepts various values, including 'auto', 'equal', or a numerical value.

import matplotlib.pyplot as plt

plt.plot(x, y)  # Assuming x and y are the data points
plt.set_aspect('equal')  # Set aspect ratio to 1:1
plt.show()

axis('equal')

Alternatively, you can use the axis('equal') function to set the aspect ratio to be equal for both axes. This ensures that the scale of the plot is consistent in both directions.

import matplotlib.pyplot as plt

plt.plot(x, y)  # Assuming x and y are the data points
plt.axis('equal')  # Set aspect ratio to be equal
plt.show()

Adjusting the range and ratio of axes in Matplotlib allows you to customize your plots and effectively communicate the intended information. Experiment with these methods to create visually appealing and informative visualizations in Python using Matplotlib.

That’s all for this blog post! I hope you found this guide helpful in understanding how to control the range and ratio of axes in Matplotlib. Happy plotting!