Matplotlib 中同一轴的多个标签位置

Multiple label positions for same axis in Matplotlib

我有一个包含很多条形的长条形图,我想提高它从轴到条形的可靠性。

假设我有下图:

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

y = np.linspace(1,-1,20)
x = np.arange(0,20)
labels = [f'Test {i}' for i in x]

fig, ax = plt.subplots(figsize=(12,8))
sns.barplot(y = y, x = x, ax=ax )
ax.set_xticklabels(labels, rotation=90)

它为我提供了以下内容:

我只知道如何在图表中全局更改标签位置。如何将轴布局更改为在中间 中根据条件更改其标签位置(在本例中,高于或低于 0)?我想要实现的是:

提前致谢=)

您可以删除现有的 x-ticks 并手动放置文本:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

y = np.linspace(1,-1,20)
x = np.arange(0,20)
labels = [f'Test {i}' for i in x]

fig, ax = plt.subplots(figsize=(12,8))
sns.barplot(y = y, x = x, ax=ax )
ax.set_xticks([]) # remove existing ticks
for i, (label, height) in enumerate(zip(labels, y)):
    ax.text(i, 0, '  '+ label+' ', rotation=90, ha='center', va='top' if height>0 else 'bottom' )
ax.axhline(0, color='black') # draw a new x-axis
for spine in ['top', 'right', 'bottom']:
    ax.spines[spine].set_visible(False) # optionally hide spines
plt.show()

这是另一种方法,我不确定它是否“更pythonic”。

  • 将现有的 x 轴移动到 y=0
  • 设置两个方向的刻度线
  • 将报价置于栏杆后面
  • 在标签前添加一些空格,使它们远离轴
  • 根据柱值重新对齐刻度标签
fig, ax = plt.subplots(figsize=(12, 8))
sns.barplot(y=y, x=x, ax=ax)
ax.spines['bottom'].set_position('zero')

for spine in ['top', 'right']:
    ax.spines[spine].set_visible(False)
ax.set_xticklabels(['    ' + label for label in labels], rotation=90)
for tick, height in zip(ax.get_xticklabels(), y):
    tick.set_va('top' if height > 0 else 'bottom')
ax.tick_params(axis='x', direction='inout')
ax.set_axisbelow(True)  # ticks behind the bars
plt.show()