简体   繁体   中英

adding custom images to matplotlib plot

I want to create a plot with two custom images below the plot, but I haven't figured out how to do it. I'm using python 3.7 and matplotlib

this is what I have so far

df = pd.DataFrame({
    'some data':[2,0,0,3,2,1,4],
    'other data':[5,1,0,5,2,2,3]
})
logo = plt.imread('A.jpg')
title = 'images'
ax = df.plot(kind='bar',x='some data',y='other data')
ax.set_title(title, fontsize=20)
ax.figure.figimage(logo, 40, 40, alpha=.15, zorder=1)

This is the result

结果

and this is what I'm trying to get.

预期的

This is the image in the plot

In order to get the images how you have them displayed in your expected output (one aligned left, one aligned right, both below plot) you can do something like this

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    'some data':[2,0,0,3,2,1,4],
    'other data':[5,1,0,5,2,2,3]
})
logo = plt.imread('A.jpg')
title = 'images'
fig, ax = plt.subplots(1)
df.plot(kind='bar',x='some data',y='other data', ax=ax)
ax.set_title(title, fontsize=20)
h = logo.shape[1]/fig.bbox.ymax
fig.subplots_adjust(0.05, h, 0.97, 0.93)
ax.figure.figimage(logo, 0, 0, alpha=.15, zorder=1)
ax.figure.figimage(logo, fig.bbox.xmax - logo.shape[0], 0, alpha=.15, zorder=1)
plt.show()

This will resize the figure to accommodate the height of the logos: logo.shape[0] is the width of the logo in pixels logo.shape[1] is the height of the logo in pixels, fig.bbox.ymax is the height of the figure in pixels. h is the fractional height of the logo which can then be used in fig.subplots_adjust to adjust the height accordingly.

It then positions one logo with the bottom left corner at offset (0, 0) and another with the bottom left corner at (fig.bbox.xmax - logo.shape[0], 0) where fig.bbox.xmax is the width of the figure in pixels. 1

This will give you something that looks like this:

在此处输入图片说明

you can export the plot as a svg file. Open this with inkscape and add the picture.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM