简体   繁体   English

如何在我的 matplotlib 图上设置文本?

[英]How can I set the text on my matplotlib figure?

I am trying to do a figure using matplotlib.我正在尝试使用 matplotlib 做一个数字。 Here is my code:这是我的代码:

import matplotlib.pyplot as plt
from matplotlib import gridspec
import matplotlib.image as mpimg


Figure = plt.figure(figsize=(9, 3))
gs = gridspec.GridSpec(1, 2)
ax = Figure.add_subplot(gs[0, 0])
ax.axis('off')
img=mpimg.imread('test.jpg')
ax.imshow(img)
ax1 = Figure.add_subplot(gs[0, 1])
ax1.axis('off')
ax1.text(0, 0, "Test", color="white", style='oblique',     ha='left', wrap=True,
         bbox={'facecolor': "#34C8EC",'boxstyle': 'round,pad=1'})
plt.show()

I got this:我懂了:

在此处输入图像描述

And I would like to have something like this:我想要这样的东西:

在此处输入图像描述

Thank you very much!非常感谢!

The first two arguments in ax1.text() are setting the position to (0,0). ax1.text() 中的前两个 arguments 将 position 设置为 (0,0)。

You need to change those values in order to change the position of the text.您需要更改这些值才能更改文本的 position。

Note that you are currently using data coordinates.请注意,您当前正在使用数据坐标。 In order to use axis coordinates, you need to provide the optional argument transform=ax.transAxes.为了使用轴坐标,您需要提供可选参数 transform=ax.transAxes。 More info in here: https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.text.html更多信息在这里: https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.text.html

They actually provide an example of a text in the centre of the image.它们实际上提供了图像中心的文本示例。 It would be:这将是:

ax1.text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
         verticalalignment='center', transform=ax.transAxes)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM