Matplotlib - rotating text on log scale where angles are incorrectly rounded

后端 未结 1 919
忘掉有多难
忘掉有多难 2021-01-25 04:10

I am trying to have text rotate onto a plot which is shown on log scale. When I compute the angles (based on the solution in this answer) the angles are getting incorrec

1条回答
  •  遥遥无期
    2021-01-25 04:55

    I updated the solution to the original question with a class RotationAwareAnnotation2, which will be better suited here. It would first transform the points into screen coordinates, and then apply the rotation.

    This this case it would look as follows.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.text as mtext
    import matplotlib.transforms as mtransforms
    
    
    class RotationAwareAnnotation2(mtext.Annotation):
        def __init__(self, s, xy, p, pa=None, ax=None, **kwargs):
            self.ax = ax or plt.gca()
            self.p = p
            if not pa:
                self.pa = xy
            kwargs.update(rotation_mode=kwargs.get("rotation_mode", "anchor"))
            mtext.Annotation.__init__(self, s, xy, **kwargs)
            self.set_transform(mtransforms.IdentityTransform())
            if 'clip_on' in kwargs:
                self.set_clip_path(self.ax.patch)
            self.ax._add_text(self)
    
        def calc_angle(self):
            p = self.ax.transData.transform_point(self.p)
            pa = self.ax.transData.transform_point(self.pa)
            ang = np.arctan2(p[1]-pa[1], p[0]-pa[0])
            return np.rad2deg(ang)
    
        def _get_rotation(self):
            return self.calc_angle()
    
        def _set_rotation(self, rotation):
            pass
    
        _rotation = property(_get_rotation, _set_rotation)
    
    
    x = np.linspace(0, 20, 100)
    f = lambda x: np.exp(x**2)
    y = f(x)
    
    fig, ax = plt.subplots()
    ax.plot(x, y)
    ax.set(yscale = 'log', ylim=(1e0, 1e180), xlim=(-1, 20), xlabel=r'$x$')
    
    annots= []
    for xi in [0,2,4,7,18]:
        an = RotationAwareAnnotation2("A", xy=(xi,f(xi)), p=(xi+.01,f(xi+.01)), ax=ax,
                                      xytext=(-1,1), textcoords="offset points", 
                                      ha="center", va="baseline", fontsize=40)
        annots.append(an)
    
    ax.set_title(r'$\exp(x^2)$', y=1.05)
    fig.savefig('logscale.pdf', format='pdf', bbox_inches='tight')
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题