Manuel Lagunas Manuel Lagunas - 1 month ago 13
Python Question

Show images in a plot using matplotlib with a coloured frame

I want to plot a graph with images on it. I am doing k-means clustering and after that, I want to show each image on its cluster with the same frame colour.

I have some code which basically places images on the graph with a black frame

fig = plt.gcf()
fig.clf()
ax = plt.subplot(111)

# add a first image
for i in range(0, len(dataset['val'].path)):
ab = AnnotationBbox(OffsetImage(img, zoom=.15, cmap='gray'),
[reduced_data[i][0], reduced_data[i][1]],
frameon=True,
xybox=(10, 10),
xycoords='data',
boxcoords="offset points",
arrowprops=dict(arrowstyle="-"))

ax.add_artist(ab)
plt.draw()
plt.show()


I was checking some tutorials on the
scickit learn
documentation and also I checked the
AnnotationBbox
and
OffsetImage
constructors in
matplotlib
webpage with no results. I was wondering if there is a way to change the frame colour of the images inserted in the plot so it matches the color I am giving to each cluster.

Answer

You can set the bounding box properties of your annotation bbox using bboxprops =dict(edgecolor='red'). A minimal example is,

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.patheffects as path_effects
import numpy as np

fig, ax = plt.subplots()
arr = np.arange(100).reshape((10, 10))
im = OffsetImage(arr)
ab1 = AnnotationBbox(im, (0.5, 0.5),
                    bboxprops =dict(edgecolor='red'))
ab2 = AnnotationBbox(im, (0.75, 0.75),
                    bboxprops =dict(edgecolor=[0.2,1.,0.5]  ))

ax.add_artist(ab1)
ax.add_artist(ab2)
plt.show()

which gives,

enter image description here

Comments