【发布时间】:2012-05-08 10:10:33
【问题描述】:
我有一个简单的线图,需要将 y 轴刻度从图的(默认)左侧移动到右侧。关于如何做到这一点的任何想法?
【问题讨论】:
标签: python matplotlib
我有一个简单的线图,需要将 y 轴刻度从图的(默认)左侧移动到右侧。关于如何做到这一点的任何想法?
【问题讨论】:
标签: python matplotlib
使用ax.yaxis.tick_right()
例如:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()
【讨论】:
sharey=True 的子图,这就会中断。
对于正确的标签,使用ax.yaxis.set_label_position("right"),即:
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()
【讨论】:
joaquin 的答案有效,但具有从轴左侧删除刻度的副作用。要解决此问题,请联系tick_right() 并致电set_ticks_position('both')。修改后的例子:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
plt.plot([2,3,4,5])
plt.show()
结果是一个两边都有刻度的图,但右边有刻度标签。
【讨论】:
只是有人问的情况(就像我做的那样),这在使用 subplot2grid 时也是可能的。例如:
import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()
它会显示这个:
【讨论】:
ax.tick_params(axis='y', which='both', labelleft='off', labelright='on')。但它不会移动ylabel
plt.gca() 获取当前坐标区对象。因此你会使用:plt.gca().yaxis.set_label_position("right")
labelleft, labelright : bool。所以应该是plt.tick_params(axis='y', which='both', labelleft=False, labelright=True) 来禁用左侧标签。还有left=False, right=True 也可以移动刻度。