gpt4 book ai didi

python - 无法反转 matplotlib 子图中的 xticks

转载 作者:行者123 更新时间:2023-11-30 22:01:37 25 4
gpt4 key购买 nike

我使用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 并没有改变。我是否缺少一些重新渲染绘图的函数调用?

以下是系统信息-

matplotlib.__version__
'2.1.1'

matplotlib.__version__numpy__
'1.7.1'

python --version
Python 2.7.15rc1

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

最佳答案

使用ax.set_xticks,您当前指定的刻度位置与列表的顺序无关。您可以传递 [0, 1, 2, 3, 4, 5],也可以传递 [5, 4, 3, 2, 1, 0]。在刻度中不会注意到差异。相反,您想要的是反转刻度标签,您应该对其执行 set_xticklabels(xticks[::-1]) 操作。有两种方法可以实现:

方法一

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

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 来获得您想要的内容

ax.set_xticks(xticks)
ax.set_xticklabels(xticks[::-1])

enter image description here

关于python - 无法反转 matplotlib 子图中的 xticks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54005499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com