Python/Matplotlib : convert Axis <=> Data coordinates systems

橙三吉。 提交于 2020-01-10 14:15:16

问题


My question is quite simple : in matplotlib, how can I easily convert coordinates in Axis system to/from Data system (Ideally I'm looking for a simple function output_coords = magic_func(input_coords) )

Actually my exact problem is : I'd like to plot an matplotlib.patches.Ellipse with his center in Axis system but his size (width & length) in Data system. But the transforms.blended_transform_factory method doesn't work in this case.

Thanks !


回答1:


To get transformations from the Axes instance ax, you can use

axis_to_data = ax.transAxes + ax.transData.inverted()
points_data = axis_to_data.transform(points_axis)
data_to_axis = axis_to_data.inverted()
numpy.testing.assert_allclose(points_axis, data_to_axis.transform(points_data))



回答2:


No immediate solution found, need to write it by myself :

def axis_data_coords_sys_transform(axis_obj_in,xin,yin,inverse=False):
    """ inverse = False : Axis => Data
                = True  : Data => Axis
    """
    xlim = axis_obj_in.get_xlim()
    ylim = axis_obj_in.get_ylim()

    xdelta = xlim[1] - xlim[0]
    ydelta = ylim[1] - ylim[0]
    if not inverse:
        xout =  xlim[0] + xin * xdelta
        yout =  ylim[0] + yin * ydelta
    else:
        xdelta2 = xin - xlim[0]
        ydelta2 = yin - ylim[0]
        xout = xdelta2 / xdelta
        yout = ydelta2 / ydelta
    return xout,yout



回答3:


Following the transforms tutorial, the simplest way is to use ax.transLimits.

output_coords = ax.transLimits.transform(input_coords)


来源:https://stackoverflow.com/questions/29107800/python-matplotlib-convert-axis-data-coordinates-systems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!