【问题标题】:Matplotlib - rotating text on log scale where angles are incorrectly roundedMatplotlib - 在角度不正确舍入的对数刻度上旋转文本
【发布时间】:2018-11-22 15:56:12
【问题描述】:

我试图让文本旋转到以对数刻度显示的图上。当我计算角度时(基于this answer 中的解决方案)角度被错误地四舍五入为 0 或 90 度。这是因为角度首先在线性比例上计算,然后再进行转换。这种在线性空间中的计算是麻烦的原因。即使在我知道梯度(线性或对数刻度)的情况下,我也不确定如何正确地将它放到图表上。

MWE

import matplotlib as mpl

rc_fonts = {
    "text.usetex": True,
    'text.latex.preview': True,
    "font.size": 50,
    'mathtext.default': 'regular',
    'axes.titlesize': 55,
    "axes.labelsize": 55,
    "legend.fontsize": 50,
    "xtick.labelsize": 50,
    "ytick.labelsize": 50,
    'figure.titlesize': 55,
    'figure.figsize': (10, 6.5),  # 15, 9.3
    'text.latex.preamble': [
        r"""\usepackage{lmodern,amsmath,amssymb,bm,physics,mathtools,nicefrac,letltxmacro,fixcmex}
        """],
    "font.family": "serif",
    "font.serif": "computer modern roman",
}
mpl.rcParams.update(rc_fonts)
import matplotlib.pylab as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, InsetPosition, mark_inset
import numpy as np


x = np.linspace(0, 20, 100)
y = np.exp(x**2)
g = 2*x*y  # Gradient.
lg = 2 * x  # Gradient on a log scale.

plt.clf()
plt.plot(x, y)
plt.yscale('log')
for x in [0,2,4,7,18]:
    angle_data = np.rad2deg(np.arctan2(2 * x * np.exp(x**2), 1))
    y = np.exp(x**2)
    angle_screen = plt.gca().transData.transform_angles(np.array((angle_data,)), np.array([x, y]).reshape((1, 2)))[0]
    plt.gca().text(x, y, r'A', rotation_mode='anchor', rotation=angle_screen, horizontalalignment='center')
plt.ylim(1e0, 1e180)
plt.xlim(-1, 20)
plt.xlabel(r'$x$')
plt.title(r'$\exp(x^2)$', y=1.05)
plt.savefig('logscale.pdf', format='pdf', bbox_inches='tight')

有什么想法?

我曾尝试使用这样一个事实,即对于非常大的函数,我可以使用 arctan(x) ~ pi/2 - arctan(1/x) 计算 90 度的差异,而前一个角度使用低角度近似值,所以只是 1/x。但是,将其插入transform_angles 后,舍入不正确。

解决方案的一个小技巧

如果我猜测图形的纵横比 (c0.6),然后还调整比例差异(x 在[0:20] 而 log10(y) 在 [0:180],则比例差异为 9 ),那么我可以得到以下结果,尽管我认为这不是特别可持续,尤其是如果我以后想调整一些东西的话。

# The 9 comes from tha fact that x is in [0:20], log10(y) is in [0, 180]. The factor of 0.6 is roughly the aspect ratio of the main plot shape.
plt.gca().text(x, y, r'A', rotation_mode='anchor', rotation=np.rad2deg(np.arctan(0.6 * x/9.0)), horizontalalignment='center')

【问题讨论】:

  • 问题在于,对于那些有问题的文本,数据坐标中的角度基本上是 90 度。
  • 正确,但令人沮丧的是,我知道对数刻度上的梯度应该是什么。
  • 我想通过arctan 使用角度在这里是不可能的。我没有太深入地研究链接问题的其他答案;也许它们更适合您的情况?

标签: python matplotlib rotation logarithm


【解决方案1】:

我用 RotationAwareAnnotation2 类更新了 solution to the original question,这将更适合这里。它首先将点转换为屏幕坐标,然后应用旋转。

本例如下所示。

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()

【讨论】:

  • 工作愉快,虽然我不确定其中的一些参数是什么,但我已经能够从示例中找出p,但是您能否添加几行文档字符串到解释其他一些? (例如pa,虽然我认为xytexttextcoords 可以查到)。
  • 我想我已经在the original answer解释过了。
猜你喜欢
  • 1970-01-01
  • 2012-07-01
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多