📜  matplotlib 轴标签 - Python (1)

📅  最后修改于: 2023-12-03 14:44:12.792000             🧑  作者: Mango

Matplotlib Plot Axis Labels - Python

Matplotlib is a powerful library in Python for creating charts and graphs. One of the essential aspects of creating a chart is adding labels to the axes. In this tutorial, we will discuss how to add labels to the X and Y axis in a Matplotlib plot.

Basic Plot

Firstly, we will create a basic plot without any labels. We will use the random module from Numpy to create random values for the X and Y-axis.

import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(10)
y = np.random.rand(10)

plt.plot(x, y)
plt.show()

Basic Plot

Adding Labels

We can add labels to the X and Y axis to the plot using the xlabel() and ylabel() functions.

plt.plot(x, y)
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
plt.show()

Plot with Labels

Customizing Labels

We can customize the labels further by changing their font size, font weight, and color using various parameters in the xlabel() and ylabel() functions.

plt.plot(x, y)
plt.xlabel('X Axis Label', fontsize=12, fontweight='bold', color='blue')
plt.ylabel('Y Axis Label', fontsize=12, fontweight='bold', color='blue')
plt.show()

Customized Labels

We can also rotate the labels using the rotation parameter in the xlabel() and ylabel() functions.

plt.plot(x, y)
plt.xlabel('X Axis Label', fontsize=12, fontweight='bold', color='blue', rotation=45)
plt.ylabel('Y Axis Label', fontsize=12, fontweight='bold', color='blue', rotation=45)
plt.show()

Rotated Labels

Conclusion

In this tutorial, we learned how to add labels to the X and Y-axis of a Matplotlib plot using the xlabel() and ylabel() functions. We also learned how to customize the labels further by changing their font size, font weight, and color, and rotating them using the rotation parameter. Adding labels to a plot is essential in providing information about the data being represented, and it helps to make the plot more informative and meaningful.