Skip to content Skip to sidebar Skip to footer

Python: Displaying A Line Of Text Outside A Matplotlib Chart

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 d

Solution 1:

Typically, you'd use annotate to do this.

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.

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

enter image description here

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

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.


Post a Comment for "Python: Displaying A Line Of Text Outside A Matplotlib Chart"