Problem
I am working with data on a logarithmic scale and would like to rotate it to fit a line. I know the model but am unsure quite what angle I should be plugging into transform_angles to recover the correct rotation. After a bit of trial and error I know the answer is around 10 degrees for the axes limits I require.
MWE
import matplotlib.pylab as plt
import numpy as np
plt.clf()
plt.yscale('log')
plt.ylim((1e-11, 1e-1)) # Other data is usually plotted and these are the ranges I need.
plt.xlim((-0.2, 7.2))
x_fit = np.linspace(0.8, 3.2, 1000)
y_ols = (lambda x: np.exp(np.log(2)*(-20.8 + -1.23 * x)))(x_fit) # I get these numbers from OLS fitting.
plt.plot(x_fit, y_ols, 'b-', dashes='', label='__nolegend__')
plt.gca().text(np.min(x_fit), 1.2*y_ols[0], r'$O(2^{{ {:.3}x }})$'.format(-1.23), rotation=-10).set_bbox(dict(facecolor='w', alpha=0.7, edgecolor='k', linewidth=0)) # There are several others lines which have been omitted.
Similar questions (keeps text rotated in data coordinate system after resizing?) only use linear axes, as do the matplotlib demos.
Remarks on the plot to answer comments
- In my full plot I use a dual axis (both on log scales) with the
twinx()feature. All the data are plotted onax1which uses a log-10 scale (as shown). (I could be more explicit and writeyscale('log', basey=10)...). Ultimately I want a base-10 axis.- The model used in making
y_olscomes from a regression fit to some original data and requires base-2. On a log scale it is easy enough to recover the gradient in any required base.
Using gradients
It is easy enough to recover the gradient on a logarithmic scale, using a mix of np.gradient and an angle (in radians) using np.arctan, but I can't seem to recover a number close to the 10 degrees (0.17 radians).
transData.transform_angles(np.array((np.mean(np.gradient(np.log10(y_ols), np.mean(np.diff(x_fit)))),)), np.array([np.min(x_fit), 1.2*y_ols[0]]).reshape((1, 2)), radians=True)[0]
gives -1.6radians (approximately -90 degrees), whereas I require a number closer to 0.17radians. Perhaps I should be using a different base, or I am doing this all wrong (hence the post).
Extras - vertical offset
As can be seen in the code, I have added a vertical offset for the anchor point when using 1.2*y_ols[0]. If a solution needs to take this into consideration then all the better.



plt.yscale('log')). You are then usingnp.log(2)which is of basee. And then you are usingnp.log10(y_ols..which is base 10. Moreover -1.6 is in radians, you need to convert it to degrees for comparison - Sheldoreexpandlogis because I desire the fitted parameters (slope and intercept) for the model in base-2 for comparison to theory. 3) I thought trying to work out the gradient in base-10 might be suitable, but as the OP shows I am unclear about how to achieve this yet. 3) Yes, -1.6 radians, (in degrees for rotation I need about -0.17 radians ~ -10 degrees). - oliversm