How to rotate text in Matplotlib – Python
In this tutorial, we will learn to rotate text in matplotlib in Python.
Steps to follow-
- Import necessary libraries
- Add text and scatter points.
- Plot the graph
Importing libraries
First of all, we will import necessary libraries(matplotlib and NumPy) which are used for rotating text in Python.
import matplotlib.pyplot as plt import numpy as np
Function add text and scatter points
We will make a function to add text to our graph.
The below code contains addtext function which adds text with the following coordinates, text in single quote, followed by props and angle of rotation.
rotate texts in Matplotlib – Python
The next snippet is for scattering the points in red color to make it a reference point. We have used ticks for showing the values on the coordinate axis whereas lim in a function in matplotlib to set the limits of coordinate axes. In the last line, we have set grid as True to see the grid lines.
def addtext(ax, props): ax.text(0.5, 0.5, ' Angle 0', props, rotation=0) ax.text(1.5, 0.5, 'Angle 45', props, rotation=45) ax.text(2.5, 0.5, 'Angle 90', props, rotation=90) ax.text(3.5, 0.5, 'Angle -45', props, rotation=-45) ax.text(4.5, 0.5, 'Angle -90', props, rotation=-90)
for x in range(0, 5): ax.scatter(x + 0.5, 0.5, color='r') ax.set_yticks([0, .5, 1]) ax.set_xticks(np.arange(0, 5.1, 0.5)) ax.set_xlim(0, 5) ax.set_ylim(0,1) ax.grid(True)
Plotting the graph
bbox is a dictionary where the values for the box are given, we have set color as yellow and padding value as 3.
bbox = {'fc': 'yellow', 'pad':3} fig, axs = plt.subplots(2, 1) addtext(axs[0], {'ha': 'center', 'va': 'center', 'bbox': bbox}) axs[0].set_ylabel('center / center') addtext(axs[1], {'ha': 'left', 'va': 'bottom', 'bbox': bbox}) axs[1].set_ylabel('left / bottom') plt.show()
The above code plots the graph as follows:
Leave a Reply