Python:在matplotlib ch外部显示一行文本

2024-10-01 13:40:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)')

现在,由于我的副标题太长(节选的第三行代码在这里报告),它会干扰Y轴的节拍,我不想这样。取而代之的是,我希望将字幕中报告的一些信息重新路由到一行文本,放在图片的底部中心,colorbar标签下。如何使用matplotlib实现这一点?在

抱歉,无法附加图像。谢谢。在


Tags: of代码图像stringtitlematplotlibshowplt
1条回答
网友
1楼 · 发布于 2024-10-01 13:40:39

通常,您将使用^{}来执行此操作。在

关键是将文本放在轴坐标系中的x坐标系(因此它与轴对齐)和y坐标系(因此它位于图形的底部),然后在点中添加偏移量,这样它就不会在图形的确切底部。在

作为一个完整的示例(我还展示了一个将extentkwarg与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()

enter image description here

其中大部分都是复制与您的示例类似的内容。关键是annotate调用。在

Annotate最常用于在相对于一个点(xytext)的位置(xytext)处的文本,并且可以选择用箭头连接文本和该点,我们将在这里跳过。在

这有点复杂,让我们把它分解一下:

^{pr2}$

希望这能有所帮助。文档中的注释指南(introdetailed)对于进一步阅读非常有用。在

相关问题 更多 >