python - 在子图中写一段文字
问题描述
我正在研究这个情节:
我需要在第一个图内写一些东西,在红线和黑线之间,我试过了,ax1.text()
但它显示了两个图之间的文本,而不是第一个图内的文本。我怎样才能做到这一点?
情节是这样安排的:
fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1, figsize = (12,7), tight_layout = True)
预先感谢您的帮助!
解决方案
没有更多的代码细节,很难猜出哪里出了问题。
matplotlib.axes.Axes.text
可以很好地在子图上显示文本框。我鼓励您查看文档(参数...)并自己尝试。
文本位置基于以下 2 个参数:
transform=ax.transAxes
: 表示坐标是相对于坐标轴边界框给出的,坐标轴(0, 0)
的左下角和(1, 1)
右上角。text(x, y,...)
: wherex
,y
是放置文本的位置。可以使用以下参数更改坐标系transform
。
这是一个例子:
# 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()
输出
推荐阅读
- javascript - 用 Python flask_socketio 反应 socket.io-client 不处理事件
- laravel - Laravel 背包 4.0。保存一个模型,然后保存另一个(不同)
- eclipse - 了解 IDE Eclipse 在构建项目时做了什么(maven 命令?)
- c++ - 构建 SquareMatrix 模板类的问题
- swift - 从 Alamofire 请求中快速打印数据
- authentication - 客户端 ssl_connect 函数返回错误证书
- excel - 将数据输入移动到下一行
- python - 如何在 PyQT 中的所有行编辑之间自动更改焦点?
- c - 是否有任何面向 C 的编译器允许内联 C?
- prolog - 如何从 Prolog 中的键值对中获取值