简体   繁体   English

Matplotlib 中同一轴的多个 label 位置

[英]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.我所知道的是如何在图表中全局更改 label position。 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)?如何根据条件(在这种情况下,高于或低于 0)将轴布局更改为在中间慢跑更改其 label position? What I want to achieve is:我想要实现的是: 目标

Thanks in advance =)提前感谢=)

You could remove the existing x-ticks and place texts manually:您可以删除现有的 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()

y=0 周围的标签条

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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