[英]matplotlib: Add an image as annotation and rotate it
我嘗試將一些圖像添加到某個位置的 matplotlib 圖形中。
圖像應獨立於底層圖形的縮放系數,但它們應具有一定的旋轉度。 (實際上,我想顯示一個飛機符號和一個具有正確航向的跑道符號,作為計算路徑的疊加,這是一個普通的 matplotlib 線圖。)
我按照此處的建議設法在正確的位置以正確的尺寸插入圖像: 如何在 matplotlib 圖形中插入圖像(圖片或照片) ,但我還無法將顯示的圖像旋轉到正確的標題。
有任何想法嗎? 老實說,我對 Matplotlib 注釋很陌生,所以我有點不知道要谷歌什么。
干杯,
菲利克斯
我不確定這是否能回答您的問題,但希望它能給您一個起點! 我還沒有確定角度計算,但再次希望它能給你一些想法。
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.