无法在matplotlib subp中反转xticks

2024-05-14 03:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我用matplotlib设计了一个子时隙。我正试着反转这个情节的xticks。请参阅示例代码-

import numpy as np
import matplotlib.pyplot as plt

# generate the data
n = 6
y = np.random.randint(low=0, high=10, size=n)
x = np.arange(n)

# generate the ticks and reverse it
xticks = range(n)
xticks.reverse()

# plot the data
plt.figure()
ax = plt.subplot(111)
ax.bar(x, y)
print xticks # prints [5, 4, 3, 2, 1, 0]
ax.set_xticks(xticks)
plt.show()

请参见下面生成的图- enter image description here

请注意xticks。即使使用了ax.set_xticks(xticks),但是xticks没有改变。我是不是错过了一些函数调用来重新呈现绘图?在

以下是系统信息-

^{pr2}$

请注意,我只想反转刻度,不想反转坐标轴。


Tags: theimportdatamatplotlibasnp请参阅plt
3条回答

使用ax.set_xticks,您当前指定的记号位置与列表的顺序是不变的。要么传递[0, 1, 2, 3, 4, 5],要么传递[5, 4, 3, 2, 1, 0]。这种区别不会在滴答声中被注意到。相反,您想要的是反转ticklabels,您应该这样做set_xticklabels(xticks[::-1])。有两种方法:

方法1

使用plt.xticks,其中第一个参数指定记号的位置,第二个参数指定相应的记号标签。具体来说,xticks将提供刻度位置,xticks[::-1]将用反转的ticklabels标记您的绘图。在

xticks = range(n)

# plot the data
plt.figure()
ax = plt.subplot(111)
ax.bar(x, y)

plt.xticks(xticks, xticks[::-1])

方法2使用ax在需要set_xticklabels的地方得到你想要的

^{pr2}$

enter image description here

使用:

# generate the data
n = 6
y = np.random.randint(low=0, high=10, size=n)
x = np.arange(n)

# generate the ticks and reverse it
xticks = range(n)
# xticks.reverse()

# plot the data
plt.figure()
ax = plt.subplot(111)
ax.bar(x, y)
# print xticks # prints [5, 4, 3, 2, 1, 0]
ax.set_xticklabels(xticks[::-1])          # <- Changed
plt.show()

out

也可以反转轴ax.set_xlim([5.5, -0.5])的顺序

import numpy as np
import matplotlib.pyplot as plt

n = 6
x = np.arange(n)
y = (x+1) **(1/2)

fig, axs = plt.subplots(1, 3, constrained_layout=True)
axs[0].bar(x, y)
axs[0].set_title('Original data')

axs[1].bar(x[::-1], y)
axs[1].set_xlim(5.5, -0.5)
axs[1].set_title('x index reversed\nand axis reversed')

axs[2].bar(x, y)
axs[2].set_xlim(5.5, -0.5)
axs[2].set_title('just axis reversed')

plt.show()

enter image description here

相关问题 更多 >