[파이썬] 축 눈금 라벨 지정

When working with plots or charts in Python, it is essential to label the tick marks on the axes correctly. This ensures that readers can easily understand the data being presented. In this blog post, we will explore how to customize and label tick marks on axes using the Python programming language.

Setting Tick Labels

To label the tick marks on the axes, we can make use of the xticks() and yticks() functions provided by the matplotlib.pyplot module. These functions allow us to set the numeric values and corresponding labels for the ticks.

import matplotlib.pyplot as plt

# generate some random data
x = range(10)
y = [i**2 for i in x]

plt.plot(x, y)

# set custom labels for x-axis
labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
plt.xticks(x, labels)

# set custom labels for y-axis
yticks = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
ytick_labels = ['zero', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
plt.yticks(yticks, ytick_labels)

plt.show()

In the above example, we first generate some random data for the x and y values. Next, we plot the data using the plot() function. To set custom labels for the x-axis, we pass the xticks() function with the list of x-values and a corresponding list of labels. Similarly, we set custom labels for the y-axis using the yticks() function.

Formatting Tick Labels

Sometimes, it may be necessary to format the tick labels to improve readability or to match a specific style. matplotlib.pyplot provides various formatting options to achieve this.

import matplotlib.pyplot as plt

# generate some random data
x = range(10)
y = [i**2 for i in x]

plt.plot(x, y)

# format x-axis tick labels as percentages
plt.gca().xaxis.set_major_formatter('{:.0f}%')

# format y-axis tick labels as currency
plt.gca().yaxis.set_major_formatter('${:.2f}')

plt.show()

In the above example, we again plot the data using the plot() function. To format the x-axis tick labels as percentages, we access the x-axis object using plt.gca().xaxis and call the set_major_formatter() function with the desired format string. Similarly, we format the y-axis tick labels as currency using the set_major_formatter() function on the y-axis object.

By customizing and formatting tick labels, we can make our plots more informative and visually appealing. Experiment with different styles and formats to find the best representation for your data.

Conclusion

In this blog post, we explored how to customize and label tick marks on axes in Python using the matplotlib.pyplot module. We learned how to set custom labels for both the x and y axes using the xticks() and yticks() functions respectively. Additionally, we saw how to format tick labels using the set_major_formatter() function to display percentages and currencies.

With these techniques, you can enhance the interpretability and aesthetics of your data visualizations. Happy coding!