简体   繁体   中英

Multiple label positions for same axis in Matplotlib

I have a long bar chart with lots of bars and I wanna improve its reability from axis to the bars.

Suppose I have the following graph:

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)

which provides me the following: 我有的

All I know is how to change the label position globally across the chart. How can I change the axis layout to be cantered in the middle and change its label position based on a condition (in this case, being higher or lower than 0)? What I want to achieve is: 目标

Thanks in advance =)

You could remove the existing x-ticks and place texts manually:

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()

y=0 周围的标签条

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM