在子图中写入文本 [英] Write a text inside a subplot
问题描述
我正在处理这个情节:
我需要在第一个图中的红线和黑线之间写一些东西,我尝试使用 ax1.text()
但它显示了两个图之间的文本,而不是第一个图中的文本一.我怎样才能做到这一点?
情节是这样设定的:
fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1, figsize = (12,7), tiny_layout = True)
预先感谢您的帮助!
没有更多的代码细节,很难猜出哪里出了问题.
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)
Thank you in advance for your help!
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
这篇关于在子图中写入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!