In a plot, the I have ylim(0,0.08)
but I am displaying only up to 0.06
. The problem with this, is that my ylabel is centered on a y-axis that is 0.08
tall instead of 0.06
tall. Is there a way to have the label centered only on the visible axis?
CodePudding user response:
import matplotlib.pyplot as plt #3.5
import numpy as np
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5))
ax1.set_yticks(np.linspace(0, 0.08, 9))
ax1.set_ylim(0, 0.08)
ax1.set_ylabel('Fraction', loc='center')
ax2.set_yticks(np.linspace(0, 0.06, 7))
ax2.set_ylim(0, 0.06)
ax2.set_ylabel('Fraction', loc='center')
CodePudding user response:
The y label gets positioned in
Here is a more general example, using np.interp
in case the lower y tick or ylim are different from 0
:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
fig, ax = plt.subplots()
t = np.linspace(0, 2 * np.pi, 500)
ax.plot(np.sin(2 * t), (np.sin(9 * t) 1) / 30)
ax.set_ylim(-0.03, 0.08)
ax.set_yticks(np.arange(0.01, 0.05 1e-6, 0.01))
ylabel = ax.set_ylabel('test label')
ylabel.set_y(np.interp(np.mean(ax.get_yticks()[[0, -1]]), ax.get_ylim(), [0, 1]))
sns.despine(ax=ax, trim=True) # cut the axis at the extreme ticks
plt.show()