Python:在matplotlib图表外显示一行文本 [英] Python: displaying a line of text outside a matplotlib chart

查看:625
本文介绍了Python:在matplotlib图表外显示一行文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由matplotlib库生成的矩阵图.我的矩阵大小为256x256,我已经有了图例和带有适当刻度的色条.由于我是Stackoverflow的新手,因此无法附加任何图像.无论如何,我使用以下代码来生成图:

I have a matrix plot produced by the matplotlib library. The size of my matrix is 256x256, and I already have a legend and a colorbar with proper ticks. I cannot attach any image due to my being new to stackoverflow. Anyhow, I use this code to generate the plot:

# 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轴的刻度,所以我不希望这样做.取而代之的是,我希望将字幕中报告的某些信息重新路由到位于颜色栏标签下方图像底部中央的一行文本.如何用matplotlib完成?

Now, being my subtitle too long (3rd line of code in the excerpt reported here), it interferes with the Y axis ticks, and I don't want this. Instead, some of the information reported in the subtitle I would like to be re-routed to a line of text to be placed at the bottom center of the image, under the colorbar label. How can this be done with matplotlib?

很抱歉,无法附加图像.谢谢.

Sorry for not being able to attach an image. Thanks.

推荐答案

通常,您将使用 annotate 来做到这一点.

Typically, you'd use annotate to do this.

关键是将带有x坐标的文本放置在坐标轴中(因此它与坐标轴对齐),将带有y坐标的文本放置在图形坐标中(因此它位于图形的底部),然后在点,因此它不在图的确切底部.

The key is to place the text with the x-coordinates in axes coordinates (so it's aligned with the axes) and the y-coordinates in figure coordinates (so it's at the bottom of the figure) and then add an offset in points so it's not at the exact bottom of the figure.

作为一个完整的示例(我还显示了一个示例,该示例将extent kwarg与imshow一起使用,以防万一您不知道它):

As a complete example (I'm also showing an example of using the extent kwarg with imshow just in case you weren't aware of it):

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调用.

Most of this is reproducing something similar to your example. The key is the annotate call.

注释通常用于在相对于点(xy)的位置(xytext)处文本,并可以选择用箭头将文本和该点连接起来,我们将在此处跳过.

Annotate is most commonly used to text at a position (xytext) relative to a point (xy) and optionally connect the text and the point with an arrow, which we'll skip here.

这有点复杂,所以我们将其分解:

This is a bit complex, so let's break it down:

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')

希望这会有所帮助.注释指南(简介

Hopefully that helps. The Annotation guides (intro and detailed) in the documentation are quite useful as further reading.

这篇关于Python:在matplotlib图表外显示一行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆