简体   繁体   English

matplotlib:添加图像作为注释并旋转它

[英]matplotlib: Add an image as annotation and rotate it

I try to add some images to a matplotlib graph at a certain position.我尝试将一些图像添加到某个位置的 matplotlib 图形中。

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.) (实际上,我想显示一个飞机符号和一个具有正确航向的跑道符号,作为计算路径的叠加,这是一个普通的 matplotlib 线图。)

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.我按照此处的建议设法在正确的位置以正确的尺寸插入图像如何在 matplotlib 图形中插入图像(图片或照片) ,但我还无法将显示的图像旋转到正确的标题。

Any ideas?有任何想法吗? Honestly, I'm quite new to Matplotlib annotations, so I kinda don't know what to google for.老实说,我对 Matplotlib 注释很陌生,所以我有点不知道要谷歌什么。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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