matplotlib 在图外显示一行文本

yqhsw0fo  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(145)

我有一个由matplotlib库生成的矩阵图。我的矩阵大小是256x256,并且我已经有了一个图例和一个带有适当刻度的颜色条。由于我是stackoverflow的新手,所以我不能附加任何图像。无论如何,我使用以下代码来生成图:

# Plotting - Showing interpolation of randomization
plt.imshow(M[-257:,-257:].T, origin='lower',interpolation='nearest',cmap='Blues', norm=mc.Normalize(vmin=0,vmax=M.max()))
title_string=('fBm: Inverse FFT on Spectral Synthesis')
subtitle_string=('Lattice size: 256x256 | H=0.8 | dim(f)=1.2 | Ref: Saupe, 1988 | Event: 50 mm/h, 15 min')
plt.suptitle(title_string, y=0.99, fontsize=17)
plt.title(subtitle_string, fontsize=9)
plt.show()

# Makes a custom list of tick mark intervals for color bar (assumes minimum is always zero)
numberOfTicks = 5
ticksListIncrement = M.max()/(numberOfTicks)
ticksList = []
for i in range((numberOfTicks+1)):
    ticksList.append(ticksListIncrement * i) 

cb=plt.colorbar(orientation='horizontal', format='%0.2f', ticks=ticksList) 
cb.set_label('Water depth [m]') 
plt.show()
plt.xlim(0, 255)
plt.xlabel('Easting (Cells)') 
plt.ylim(255, 0)
plt.ylabel('Northing (Cells)')

现在,我的副标题太长了(这里报告的摘录中的第3行代码),它干扰了Y轴刻度,我不希望这样。相反,副标题中报告的一些信息我希望被重新路由到一行文本中,放置在图像的底部中心,在colorbar标签下。如何使用matplotlib实现这一点?

kmbjn2e3

kmbjn2e31#

通常,您会使用annotate来执行此操作。
关键是将文本的x坐标放置在轴坐标中(这样它就与轴对齐),y坐标放置在图形坐标中(这样它就在图形的底部),然后添加一个以点为单位的偏移,这样它就不在图形的确切底部。
作为一个完整的示例(我还展示了一个将extent kwarg与imshow一起使用的示例,以防您不知道):

import numpy as np
import matplotlib.pyplot as plt

data = np.random.random((10, 10))

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', cmap='gist_earth', aspect='auto',
               extent=[220, 2000, 3000, 330])

ax.invert_yaxis()
ax.set(xlabel='Easting (m)', ylabel='Northing (m)', title='This is a title')
fig.colorbar(im, orientation='horizontal').set_label('Water Depth (m)')

# Now let's add your additional information
ax.annotate('...Additional information...',
            xy=(0.5, 0), xytext=(0, 10),
            xycoords=('axes fraction', 'figure fraction'),
            textcoords='offset points',
            size=14, ha='center', va='bottom')

plt.show()

大部分内容都与您的示例类似,关键是annotate调用。
注解最常用于相对于点(xy)的位置(xytext)处的文本,并且可以选择用箭头连接文本和点,我们在这里跳过。
这有点复杂,所以让我们把它分解一下:

ax.annotate('...Additional information...',  # Your string

            # The point that we'll place the text in relation to 
            xy=(0.5, 0), 
            # Interpret the x as axes coords, and the y as figure coords
            xycoords=('axes fraction', 'figure fraction'),

            # The distance from the point that the text will be at
            xytext=(0, 10),  
            # Interpret `xytext` as an offset in points...
            textcoords='offset points',

            # Any other text parameters we'd like
            size=14, ha='center', va='bottom')

希望这有帮助。文档中的注解指南(introdetailed)作为进一步阅读非常有用。

相关问题