我想在图表上绘制带有图像的图形。我正在进行k-means聚类,之后我想在每个聚类上显示图像,并使用相同的边框颜色。
我有一些代码,基本上是将图像放置在图表上,并带有黑色边框
fig = plt.gcf()fig.clf()ax = plt.subplot(111)# 添加第一张图像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
文档中查了一些教程,我也查看了matplotlib
网页上的AnnotationBbox
和OffsetImage
构造函数,但没有结果。我想知道是否有办法更改插入图表中图像的边框颜色,使其与我为每个聚类指定的颜色相匹配。
回答:
你可以使用bboxprops=dict(edgecolor='red')
来设置你的AnnotationBbox的边界框。一个最小的示例,
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.offsetbox import OffsetImage, AnnotationBboxfig, 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()
这将得到,