Matplotlib ytick的绝对值

Matplotlib ytick's absolute value

在 matplotlib 中,如何在 yticks 中使用绝对值?

例如,100、50、0、50、100、150。

您可以手动替换 y 轴刻度标签。

例如:

ax.set_yticks(range(-100, 200, 50))
ax.set_yticklabels([abs(y) for y in range(-100, 200, 50)])

使用 get_yticks 获取当前报价,修改它然后使用 set_yticklabels。请参阅下面的示例。

%matplotlib inline
import matplotlib.pyplot as plt
from math import trunc
a = np.random.rand(100)*30-20

plt.figure()

fig,ax = plt.subplots()

ax.bar(np.arange(len(a)), a)

ticks =  ax.get_yticks()

# set labels to absolute values and with integer representation
ax.set_yticklabels([int(abs(tick)) for tick in ticks])

plt.show()

由于 ax.get_yticks() returns numpy.ndarray 对象,可以直接在其上使用 abs 函数,这导致更简洁的解决方案:

ax.set_yticklabels(abs(ax.get_yticks()))