首页 > 解决方案 > matplotlib:添加图像作为注释并旋转它

问题描述

我尝试在某个位置将一些图像添加到 matplotlib 图中。

图像应独立于底层图形的缩放因子,但它们应具有一定的旋转。(实际上,我想显示一个带有正确航向的飞机符号和一个跑道符号作为计算路径的覆盖,这是一个普通的 matplotlib 线图。)

我按照此处的建议设法以正确的尺寸将图像插入到正确的位置: How to insert an image (a picture or a photo) in a matplotlib figure,但我还不能将显示的图像旋转到正确的标题。

有任何想法吗?老实说,我对 Matplotlib 注释很陌生,所以我有点不知道谷歌要做什么。

干杯,
菲利克斯

标签: pythonmatplotlib

解决方案


我不确定这是否能回答你的问题,但希望它能给你一个起点!我还没有确定角度计算,但再次希望它能给你一些想法。

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

在此处输入图像描述


推荐阅读