Introduction
Matplotlib is a powerful data visualization library in Python. It provides a wide range of tools to create graphs and plots in Python. In this tutorial, we will learn how to create text and mathtext using pyplot.
VM Tips
After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.
Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.
If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.
Import Required Libraries
First, we need to import the required libraries. We will import numpy and matplotlib.pyplot libraries.
import matplotlib.pyplot as plt
import numpy as np
Create Data
Next, we will create data for the plot. We will create a sine wave using numpy library.
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
Plot the Graph
Now, we will plot the graph using plot() method of pyplot library.
plt.plot(t, s)
Add Text to the Graph
We can add text to the graph using text() method of pyplot library. We will add "Hello, world!" text at coordinates (0, -1).
plt.text(0, -1, r'Hello, world!', fontsize=15)
Add Title, X-label, and Y-label
We can add title, X-label, and Y-label to the graph using title(), xlabel(), and ylabel() methods of pyplot library. We will add "Voltage vs Time" as the title, "Time [s]" as X-label, and "Voltage [mV]" as Y-label.
plt.title(r'Voltage vs Time', fontsize=20)
plt.xlabel('Time [s]')
plt.ylabel('Voltage [mV]')
Show the Graph
Finally, we will show the graph using show() method of pyplot library.
plt.show()
Summary
In this tutorial, we learned how to create text and mathtext using pyplot. We learned how to add text to the graph, how to add title, X-label, and Y-label to the graph, and how to show the graph using pyplot.