5. Customizing Legends & Ticks
Mastering Legends
A legend is essential for identifying data series within a plot. To generate a legend, pass a label argument to your plotting function and then call 'plt.legend()'. You can control positioning using the loc parameter, which accepts strings like 'upper right' or best to let Matplotlib automatically find the least obstructive location.
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [1, 4, 9], label='Growth') plt.legend(loc='upper left') plt.show()
Adjusting Axis Limits
Sometimes auto-scaling does not present the best view of your data. Use 'plt.xlim()' and 'plt.ylim()' to manually define the range of your axes. These functions accept a tuple of '(min, max)' values, allowing you to zoom in on specific regions or include extra space around the edges of your data points.
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [1, 4, 9]) plt.xlim(0, 5) plt.ylim(0, 15) plt.show()
Customizing Ticks and Labels
Ticks provide the framework for reading values from your axes. You can modify their positions using 'plt.xticks()' and 'plt.yticks()'. These functions allow you to specify the exact tick locations in a list and provide custom labels, which is useful when dealing with categorical data or non-linear time series.
rotation parameter in plt.xticks is very helpful when your tick labels are long strings.
import matplotlib.pyplot as plt plt.plot([0, 1, 2], [10, 20, 30]) plt.xticks([0, 1, 2], ['Start', 'Mid', 'End'], rotation=45) plt.show()
Knowledge Check
Ready to test your understanding of 5. Customizing Legends & Ticks?