matplotlib中的补丁旋转未按预期工作

1 投票
1 回答
4153 浏览
提问于 2025-04-16 23:57

我想在一个matplotlib图表上叠加一个旋转的矩形。我有以下代码:

    fig = Figure((3.8, 3.4))
    subp = fig.add_subplot(111)
    
    fig.axes[0].set_autoscale_on(False)
    fig.axes[0].set_ylim([float(self.getConfig('GUI', 'chartmin', '-1')),float(self.getConfig('GUI', 'chartmax','4' ))])
    fig.axes[0].set_xlim([dataSet[0][2]/1000,dataSet[-1][2]/1000])
    fig.axes[0].yaxis.grid(True, which='major') 
    
    timevals = []
    dataPoints = []

#timevals and datapoints are then populated and added to chart correctly, code removed for easier reading

    subp.plot(timevals, dataPoints)
    rect = matplotlib.patches.Rectangle( ((dataSet[0][2]/1000)+3,0), width=1.5, height=3, alpha=0.50)
    rect2 = matplotlib.patches.Rectangle( ((dataSet[0][2]/1000)+3,0), width=1.5, height=3, color="red", alpha=0.50)
    
    t_start = subp.transData
    t = matplotlib.transforms.Affine2D().rotate_deg(-45)
    t_end = t_start + t  
    rect.set_transform(t_end)
    subp.add_patch(rect)
    subp.add_patch(rect2)

dataSet[0][2]/1000)+3 这个表达式给出了图表时间序列的起点,加上3秒。

生成的图表y值在0到4之间,而x值可以是任何数(这是一个力(y)对时间(x)的图)。

我希望上面的代码输出的结果是,rect2(蓝色的那个)和rect(红色的那个)是一样的,只是旋转了45度。但实际上我得到的是这个:

这个图确实是旋转了45度,但同时也发生了平移。我试过使用rotate_deg_around(0,0,-45),但这似乎没有帮助。有人能看出我哪里做错了吗,还是我对rotate的理解有误?

1 个回答

6

默认情况下,旋转是围绕原点进行的。你可能不想让蓝色矩形围绕原点旋转,而是想让它围绕自己的中心点旋转。这其实可以理解为,先把矩形移动到原点,让它的中心点对齐原点,然后进行旋转,最后再把它移回原来的位置。

幸运的是,matplotlib 提供了一个很方便的功能,可以让你更轻松地完成这个操作:rotate_deg_around(x, y, degrees)。只需要传入矩形的中心点,你就可以顺利完成旋转了。

撰写回答