[파이썬] 축 로그 스케일 설정

When plotting data in Python, it is often necessary to adjust the scale of the axes to better visualize the data. One common technique is to use a logarithmic scale for one or both of the axes. In this blog post, we will explore how to set logarithmic scales for axes in Python using the popular plotting library, matplotlib.

Setting Logarithmic Scale for a Single Axis

To set a logarithmic scale for a single axis, we can use the set_xscale() or set_yscale() method of the matplotlib axes object.

import matplotlib.pyplot as plt

# Generate some sample data
x = [1, 10, 100, 1000]
y = [1, 2, 3, 4]

# Create a scatter plot
plt.scatter(x, y)

# Set x-axis to logarithmic scale
plt.xscale('log')

# Set y-axis to logarithmic scale
plt.yscale('log')

# Show the plot
plt.show()

In the example code above, we first import matplotlib and create two lists x and y for our sample data. We then create a scatter plot using the scatter() function. The xscale('log') and yscale('log') methods set the x-axis and y-axis scales to logarithmic, respectively. Finally, we call show() to display the plot.

Setting Logarithmic Scale for Both Axes

If we want to set a logarithmic scale for both the x-axis and the y-axis, we can use the set_xscale() and set_yscale() methods together.

import matplotlib.pyplot as plt

# Generate some sample data
x = [1, 10, 100, 1000]
y = [1, 2, 3, 4]

# Create a scatter plot
plt.scatter(x, y)

# Set both x-axis and y-axis to logarithmic scale
plt.xscale('log')
plt.yscale('log')

# Show the plot
plt.show()

Similarly, we first import matplotlib and create our sample data. We then create a scatter plot. Calling xscale('log') and yscale('log') with no argument sets both axes to logarithmic scale. Finally, we call show() to display the plot.

Conclusion

Using a logarithmic scale can be a useful technique when plotting data that spans a wide range of values. By setting the logarithmic scale for one or both axes, we can better visualize the data and identify trends that might not be apparent on a linear scale. Matplotlib provides convenient methods to set logarithmic scales for axes in Python, making it easy to apply this technique to our plots.