我有一个由 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 轴刻度,我不希望这样。相反,我想将副标题中报告的一些信息重新路由到一行文本,放置在图像的底部中心,在颜色栏标签下。如何使用 matplotlib 完成此操作?
抱歉无法附上图片。谢谢。
最佳答案
通常,您会使用 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
调用。
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')
关于python - 在绘图外显示一行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32742511/