【问题标题】:pyplot and semilogarithmic scale: how to draw a circle with transformpyplot 和半对数刻度:如何用变换画一个圆
【发布时间】:2013-09-24 15:42:57
【问题描述】:

我想在用 pyplot 绘制的图中画一个圆圈,但我需要在 x 轴上使用对数刻度。

我愿意:

ax = plt.axes()

point1 = plt.Circle((x,y), x, color='r',clip_on=False, 
                    transform = ax.transAxes, alpha = .5)

plt.xscale('log')

current_fig = plt.gcf()

current_fig.gca().add_artist(point1)

如您所见,我希望圆的半径等于 x 坐标。

我的问题是,如果我使用,就像这里写的那样,transAxes,那么我得到的圆实际上是一个圆(否则它会在 x 上拉伸,看起来像一个被切成两半的椭圆),但是 x坐标为 0。另一方面,如果我使用 transData 而不是 transAxes,那么我会得到正确的 x 坐标值,但圆会再次被拉伸并切成两半。

我不介意拉伸,但我不喜欢切割,我希望它至少是一个完整的椭圆。

知道如何获得我想要的吗?

【问题讨论】:

    标签: matplotlib geometry logarithm


    【解决方案1】:

    可能最简单的方法是使用绘图标记而不是Circle。例如:

    ax.plot(x,y,marker='o',ms=x*5,mfc=(1.,0.,0.,0.5),mec='None')
    

    这将为您提供一个始终看起来是“圆形”的圆,并将以正确的 x,y 坐标为中心,尽管它的大小与 x 和 y 比例无关。如果您只关心中心位置,那么您可以乱用ms=,直到它看起来正确为止。

    执行此操作的更通用方法是为圆构造一个新的复合变换 - 您应该查看this tutorial on transformations。基本上,从图形到数据空间的转换是这样构造的:

    transData = transScale + (transLimits + transAxes)
    

    其中transScale 处理数据的任何非线性(例如对数)缩放,transLimits 将数据的 x 和 y 限制映射到轴的单位空间,transAxes 映射坐标轴边界框进入显示空间。

    您希望保持圆看起来像一个圆/椭圆(即不根据 x 轴的对数缩放对其进行扭曲),但您仍希望将其转换为数据坐标中的正确中心位置。为此,您可以构建一个缩放的翻译,然后将它与transLimitstransAxes 结合起来:

    from matplotlib.transforms import ScaledTranslation
    
    ax = plt.axes(xscale='log')
    x,y = 10,0
    ax.set_ylim(-11,11)
    ax.set_xlim(1E-11,1E11)
    
    # use the axis scale tform to figure out how far to translate 
    circ_offset = ScaledTranslation(x,y,ax.transScale)
    
    # construct the composite tform
    circ_tform = circ_offset + ax.transLimits + ax.transAxes
    
    # create the circle centred on the origin, apply the composite tform
    circ = plt.Circle((0,0),x,color='r',alpha=0.5,transform=circ_tform)
    ax.add_artist(circ)
    plt.show()
    

    显然,x 轴上的缩放会有点奇怪和随意 - 您需要尝试构建转换的方式才能得到您想要的结果。

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 2021-06-14
      • 2016-06-09
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多