使用带有彩色边框的matplotlib在绘图中显示图像

时间:2016-10-31 12:39:33

标签: python matplotlib plot machine-learning

我想在其上绘制带有图像的图表。我正在进行k-means聚类,之后,我想在其簇上显示具有相同帧颜色的每个图像。

我有一些代码基本上将图像放在带有黑框的图形上

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

我正在检查scickit learn文档中的一些教程,还检查了AnnotationBbox网页中的OffsetImagematplotlib构造函数,但没有结果。我想知道是否有办法改变插图中插入的图像的帧颜色,以便它与我给每个聚类的颜色相匹配。

1 个答案:

答案 0 :(得分:5)

您可以使用bboxprops=dict(edgecolor='red')设置AnnotationBbox的边界框。 一个最小的例子,

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

fig, ax = plt.subplots()
im = OffsetImage(np.arange(100).reshape((10, 10)))
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()

给出,

enter image description here