Aligning the edge of a text field using an image corner

I'm looking for a way to exactly align (overlay) the corner edge of my image with the angle and edge of the edge of the text box (bbox or other)

This code:

import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
ax.imshow(np.random.random((256,256)), cmap=plt.get_cmap("viridis"))
ax.axis("off")

ax.annotate(
    s = 'image title', 
    xy=(0, 0), 
    xytext=(0, 0), 
    va='top',
    ha='left',
    fontsize = 15,
    bbox=dict(facecolor='white', alpha=1),
    )
plt.show()

Single image

As you can see, the edges of the text box are outside the image. For my life, I cannot find a consistent way to align the angle of a text field with the angle of an image. Ideally, I would like the alignment not to depend on the font size and pixel size of the image, but that could be too much.

Finally, I would like to achieve this using an image grid, for example, a second example.

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 8))
images = 4*[np.random.random((256,256))]

gs = gridspec.GridSpec(
    nrows=2, 
    ncols=2,
    top=1., 
    bottom=0., 
    right=1., 
    left=0., 
    hspace=0.,
    wspace=0.,
)
for g, i in zip(gs, range(len(images))):
    ax = plt.subplot(g)
    im = ax.imshow(
        images[i],
        cmap=plt.get_cmap("viridis")
    )
    ax.set_xticks([])
    ax.set_yticks([])
    ax.annotate(
        s = 'image title', 
        xy=(0, 0), 
        xytext=(0, 0), 
        va='top',
        ha='left',
        fontsize = 15,
        bbox=dict(facecolor='white', alpha=1),
    )

enter image description here

+4
source share
2 answers

. , pad (, pad = 0 ). , , ( ).

+2

P- . , x y xy. , . , ax.annotate, .

fig, ax = plt.subplots(1)
ax.imshow(np.random.random((256,256)), cmap=plt.get_cmap("viridis"))
ax.axis("off")

padding = 5
ax.annotate(
    s = 'image title', 
    fontsize = 12,

    xy=(0, 0), 
    xytext=(padding-1, -(padding-1)), 
    textcoords = 'offset pixels',
    bbox=dict(facecolor='white', alpha=1, pad=padding),
    va='top',
    ha='left',
    )
plt.show()

Aligned Image

, x , xytext xytext=(padding, -(padding-1)).

Aligned grid of four images

+2

Source: https://habr.com/ru/post/1648502/


All Articles