【发布时间】: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