Matplotlib: 极坐标投影 transData.transform会给出错误的值

2024-06-23 23:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在极坐标图的某个特定点插入一个小图标。你知道吗

据我所知,fig.figimage(image, x, y)接收x,y作为显示坐标。我使用ax.transData.transform_point((theta, radius)),但这不能正常工作。你知道吗

我的代码如下:

from numpy import *
from matplotlib.pyplot import *

t = arange(0, 2*pi, 0.01)
r = ones(t.size)

fig = gcf()
ax = fig.add_subplot(111, projection='polar')
ax.plot(t, r)

x, y = ax.transData.transform((pi/4, 1.0))
img = imread('die.png')
fig.figimage(img, x, y)

show()

Here's the result,而img的左下角应该以45度和半径1接触蓝线。你知道吗


Tags: 代码fromimageimportimgpifigtransform
1条回答
网友
1楼 · 发布于 2024-06-23 23:19:37

您需要先绘制图形,然后变换才能为您提供正确的坐标。你知道吗

fig.canvas.draw()
x, y = ax.transData.transform((pi/4, 1.0))

这是因为只有在实际绘制图形时才确定极坐标图的轴位置。在动手之前尝试变换某些东西会导致坐标错误。你知道吗

一般来说,我建议在这种情况下使用AnnotationBbox而不是figimage。你知道吗

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

t = np.arange(0, 2*np.pi, 0.01)
r = np.ones(t.size)

fig = plt.gcf()
ax = fig.add_subplot(111, projection='polar')
ax.plot(t, r)

img = plt.imread('https://i.stack.imgur.com/9qe6z.png')

imagebox = OffsetImage(img, zoom=0.2)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, (np.pi/4, 1.0),
                    box_alignment=(0., 0),
                    xycoords='data', pad=0)

ax.add_artist(ab)

plt.show()

enter image description here

相关问题 更多 >

    热门问题