0

I'm trying to center the y label horizontally in my plot. I want the labels to show up just as they would ordinarily, except centered instead of along the side of the plot.

import matplotlib
import matplotlib.pyplot as plt

y = np.arange(0, 11, 1)
x = np.arange(0, 11, 1)
fig, ax = plt.subplots(figsize=(10,50))
ax.xaxis.tick_top() 
offset = matplotlib.transforms.ScaledTranslation(0.5, 0, fig.transFigure)
for label in ax.yaxis.get_majorticklabels():
    label.set_transform(label.get_transform() + offset)
plt.margins(y=0.005)
plt.yticks(np.arange(0, len(y)+1, 1))
plt.plot(y, x, lw=2)
plt.show()

(If you noticed I have the x and y arrays swapped, it's because I'm trying to rotate my graph too).

I've gotten something close to what I'd like, although I'm not sure this is actually centered, plus it seems to shove down the labels a bit, which is not what I want. I am not sure why this is happening because I only set the x value in my offset.

How can I get the labels centered without moving downwards?

brienna
  • 1,415
  • 1
  • 18
  • 45
  • This post my help. https://stackoverflow.com/q/54007628/6361531 – Scott Boston Jun 17 '20 at 00:28
  • Maybe even better this one: https://stackoverflow.com/a/49449590/2588210. – Christian K. Jun 17 '20 at 00:50
  • @ChristianK. that's actually the one I got the idea from for my current code. I'm not sure why my code is pushing down the labels though. – brienna Jun 17 '20 at 06:38
  • @briennakh It seems you need a different transformation: `fig.dpi_scale_trans` rather then `fig.transFigure`. In that case the units of the offset values are inch not pixels. It wuld be interesting though to understand why `fig.transFigure` does something else. Maybe you could ask the author of that post. – Christian K. Jun 17 '20 at 11:43

0 Answers0