简体   繁体   中英

matplotlib: Add an image as annotation and rotate it

I try to add some images to a matplotlib graph at a certain position.

The images shall be independent of the zoom factor of the underlying graph, but they shall have a certain rotation. (Actually, I'd like to display an aircraft symbol and a runway symbol with the correct heading as an overlay to the calculated path which is an ordinary matplotlib line plot.)

I managed to insert the images at the correct postiion with the correct size by following the advice here: How to insert an image (a picture or a photo) in a matplotlib figure , but I was not able yet to rotate the displayed images into the correct headings.

Any ideas? Honestly, I'm quite new to Matplotlib annotations, so I kinda don't know what to google for.

Cheers,
Felix

I'm not sure if this answers your question, but hopefully it will give you a starting point! I haven't nailed the angle calculation, but again, hope it gives you some ideas.

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

# Set x value of image centre
x_image = 7


# Set up matplotlib figure with axis
fig, ax = plt.subplots()


# Create arbitrary curve for path
def f_curve(x):
    return 0.1*x**2

x = np.arange(0,10,0.01)   # start,stop,step
y = f_curve(x)

plt.plot(x, y)


# create spline function (to get image centre y-value and derivative at that point)
f = interpolate.InterpolatedUnivariateSpline(x, y, k=1)
xs = np.linspace(min(x), max(x), 100)
plt.plot(xs, f(xs), 'g', lw=3)


# Get y-value for image centre 
# (replace this with your own y-value if you already know it)
y_image = f(x_image)


# Read in image
img = plt.imread('batman.png')

# Convert image into numpy array
image_arr = np.array(img)

# Calculate the derivative of the path curve at x_image to get the angle of rotation required
angle = np.rad2deg(f.derivative()(x_image))-90

# Rotate image
image_arr = ndimage.rotate(image_arr, angle, reshape=True)

# inspired by 
# https://moonbooks.org/Articles/How-to-insert-an-image-a-picture-or-a-photo-in-a-matplotlib-figure/
imagebox = OffsetImage(image_arr, zoom=0.2)
ab = AnnotationBbox(imagebox, (x_image, y_image),bboxprops={'edgecolor':'none','alpha':0.1})
ax.add_artist(ab)
plt.draw()

plt.show()

在此处输入图片说明

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