matplotlib y-axis label on right side

Is there a simple way to put the y-axis label on the right-hand side of the plot? I know that this can be done for the tick labels using ax.yaxis.tick_right(), but I would like to know if it can be done for the axis label as well.

One idea which came to mind was to use

ax.yaxis.tick_right()
ax2 = ax.twinx()
ax2.set_ylabel('foo')

However, this doesn't have the desired effect of placing all labels (tick and axis labels) on the right-hand side, while preserving the extent of the y-axis. In short, I would like a way to move all the y-axis labels from the left to the right.

146466 次浏览

看起来你可以用:

ax.yaxis.set_label_position("right")
ax.yaxis.tick_right()

有关示例,请参见 给你

如果你想按照 matplotlib中给出的例子,创建一个轴线两边都有标签的图形,但是不需要使用 subplots()函数,以下是我的解决方案:

from matplotlib import pyplot as plt
import numpy as np


ax1 = plt.plot()
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
plt.plot(t,s1,'b-')
plt.xlabel('t (s)')
plt.ylabel('exp',color='b')


ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
plt.ylabel('sin', color='r')
plt.show()

(抱歉重提这个问题)

我知道这是一个肮脏的伎俩,但是如果你不想下降到轴处理和停留在 plt命令,你可以使用 labelpad标量参数定位您的标签到右侧的图形。经过一些尝试和错误,以及精确的标量值可能(?)和你的身材尺寸有关。

例如:

# move ticks
plt.tick_params(axis='y', which='both', labelleft=False, labelright=True)


# move label
plt.ylabel('Your label here', labelpad=-725, fontsize=18)

前面的答案已经过时了,下面是上面示例的最新代码:

import numpy as np
import matplotlib.pyplot as plt


t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)


fig, ax1 = plt.subplots()


color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)


ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis


color = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)


fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

来自 给你