how to put text on a subplot matplotlib
- User
how to put text on a subplot matplotlib
Assistant
Adding text to a subplot in Matplotlib can be accomplished in several ways, depending on where you want the text to appear (e.g., inside the plot area, at a specific data point, or outside the plot as a title/subtitle). Below are examples of how to place text in different locations within a subplot:
1. Adding Text Inside the Plot Area
To add text inside the plot, you can use the
textfunction, specifying thexandycoordinates where the text should appear, relative to the plot's data coordinates. Thehaparameter is used to specify horizontal alignment ('center', 'left', 'right').pythonimport matplotlib.pyplot as plt import numpy as np # Sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Create a figure and a set of subplots fig, ax = plt.subplots(2, 1, figsize=(8, 6)) # Plot on the first subplot ax[0].plot(x, y) # Add text inside the first subplot ax[0].text(5, 0.5, 'Text inside plot', ha='center', fontsize=14, color='red') # Plot on the second subplot for demonstration ax[1].plot(x, np.cos(x)) # Layout so plots do not overlap fig.tight_layout() plt.show()2. Annotating Specific Data Points
If you want to highlight a specific data point with text, you can use the
annotatefunction, which offers more flexibility, including the ability to specify the location of the text relative to the point and to draw an arrow from the text to the point. Thexytextparameter is used to specify the location of the text relative to the data point, andarrowpropsis used to customize the arrow's appearance.pythonimport matplotlib.pyplot as plt import numpy as np # Sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Create a figure and a set of subplots fig, ax = plt.subplots(2, 1, figsize=(8, 6)) # Plot on the first subplot ax[0].plot(x, y) # Annotate a specific point ax[0].annotate('Peak', xy=(np.pi/2, 1), xytext=(np.pi/2+1, 0.5), arrowprops=dict(facecolor='black', shrink=0.05), fontsize=13) # Plot on the second subplot for demonstration ax[1].plot(x, np.cos(x)) # Layout so plots do not overlap fig.tight_layout() plt.show()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.