Issue
I'm working on this plot:
I need to write something inside the first plot, between the red and the black lines, I tried with ax1.text()
but it shows the text between the two plots and not inside the first one. How can I do that?
The plot was set out as such:
fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1, figsize = (12,7), tight_layout = True)
Solution
Without more code details, it's quite hard to guess what is wrong.
The matplotlib.axes.Axes.text
works well to show text box on subplots. I encourage you to have a look at the documentation (arguments...) and try by yourself.
The text location is based on the 2 followings arguments:
transform=ax.transAxes
: indicates that the coordinates are given relative to the axes bounding box, with(0, 0)
being the lower left of the axes and(1, 1)
the upper right.text(x, y,...)
: wherex
,y
are the position to place the text. The coordinate system can be changed using the below parametertransform
.
Here is an example:
# import modules
import matplotlib.pyplot as plt
import numpy as np
# Create random data
x = np.arange(0,20)
y1 = np.random.randint(0,10, 20)
y2 = np.random.randint(0,10, 20) + 15
# Create figure
fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1, figsize = (12,7), tight_layout = True)
# Add subplots
ax1.plot(x, y1)
ax1.plot(x, y2)
ax2.plot(x, y1)
ax2.plot(x, y2)
# Show texts
ax1.text(0.1, 0.5, 'Begin text', horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes)
ax2.text(0.9, 0.5, 'End text', horizontalalignment='center', verticalalignment='center', transform=ax2.transAxes)
plt.show()
output
Answered By - Alexandre B.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.