在子图中写入文本 [英] Write a text inside a subplot

查看:28
本文介绍了在子图中写入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理这个情节:

我需要在第一个图中的红线和黑线之间写一些东西,我尝试使用 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,...): where x, y are the position to place the text. The coordinate system can be changed using the below parameter transform.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆