matplotlib 在图外显示一行文本

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

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

  1. # Plotting - Showing interpolation of randomization
  2. plt.imshow(M[-257:,-257:].T, origin='lower',interpolation='nearest',cmap='Blues', norm=mc.Normalize(vmin=0,vmax=M.max()))
  3. title_string=('fBm: Inverse FFT on Spectral Synthesis')
  4. subtitle_string=('Lattice size: 256x256 | H=0.8 | dim(f)=1.2 | Ref: Saupe, 1988 | Event: 50 mm/h, 15 min')
  5. plt.suptitle(title_string, y=0.99, fontsize=17)
  6. plt.title(subtitle_string, fontsize=9)
  7. plt.show()
  8. # Makes a custom list of tick mark intervals for color bar (assumes minimum is always zero)
  9. numberOfTicks = 5
  10. ticksListIncrement = M.max()/(numberOfTicks)
  11. ticksList = []
  12. for i in range((numberOfTicks+1)):
  13. ticksList.append(ticksListIncrement * i)
  14. cb=plt.colorbar(orientation='horizontal', format='%0.2f', ticks=ticksList)
  15. cb.set_label('Water depth [m]')
  16. plt.show()
  17. plt.xlim(0, 255)
  18. plt.xlabel('Easting (Cells)')
  19. plt.ylim(255, 0)
  20. plt.ylabel('Northing (Cells)')

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

kmbjn2e3

kmbjn2e31#

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

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. data = np.random.random((10, 10))
  4. fig, ax = plt.subplots()
  5. im = ax.imshow(data, interpolation='nearest', cmap='gist_earth', aspect='auto',
  6. extent=[220, 2000, 3000, 330])
  7. ax.invert_yaxis()
  8. ax.set(xlabel='Easting (m)', ylabel='Northing (m)', title='This is a title')
  9. fig.colorbar(im, orientation='horizontal').set_label('Water Depth (m)')
  10. # Now let's add your additional information
  11. ax.annotate('...Additional information...',
  12. xy=(0.5, 0), xytext=(0, 10),
  13. xycoords=('axes fraction', 'figure fraction'),
  14. textcoords='offset points',
  15. size=14, ha='center', va='bottom')
  16. plt.show()

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

  1. ax.annotate('...Additional information...', # Your string
  2. # The point that we'll place the text in relation to
  3. xy=(0.5, 0),
  4. # Interpret the x as axes coords, and the y as figure coords
  5. xycoords=('axes fraction', 'figure fraction'),
  6. # The distance from the point that the text will be at
  7. xytext=(0, 10),
  8. # Interpret `xytext` as an offset in points...
  9. textcoords='offset points',
  10. # Any other text parameters we'd like
  11. size=14, ha='center', va='bottom')

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

展开查看全部

相关问题