首页 > 解决方案 > 使用 set_yticklabels 时如何反转 (invert_yaxis())

问题描述

我正在尝试使用 .invert_yaxis(),但使用 set_yticklabels 时会出现错误消息。
无论如何在下面的代码上使用反转?

import matplotlib.pyplot as plt
import numpy as np

x = [1.0, 1.1, 2.0, 5.7]
y = np.arange(len(x))
fsize=(2,2)
fig, ax = plt.subplots(1,1,figsize=fsize)

ax.set_yticklabels(list(' abcd')) #if the abcd is data which get from upper code

ax.barh(y,x,align='center',color='grey')
plt.show()

标签: pythonmatplotlibjupyter-notebook

解决方案


使用set_yticklabels时强烈建议先设置set_yticks。一般来说,matplotlib 在内部决定将刻度放在哪里。代码中的微小更改可能会将刻度线放在不同的位置。通过明确使用set_yticks,您可以确定他们的位置。

import matplotlib.pyplot as plt
import numpy as np

x = [1.0, 1.1, 2.0, 5.7]
y = np.arange(len(x))
fsize=(2,2)
fig, ax = plt.subplots(1,1,figsize=fsize)

ax.barh(y,x,align='center',color='grey')
ax.set_yticks(y)
ax.set_yticklabels(list('abcd')) #if the abcd is data which get from upper code
ax.invert_yaxis()
plt.show()

结果图


推荐阅读