繁体   English   中英

Matplotlib 中同一轴的多个 label 位置

[英]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)

这为我提供了以下内容: 我有的

我所知道的是如何在图表中全局更改 label position。 如何根据条件(在这种情况下,高于或低于 0)将轴布局更改为在中间慢跑更改其 label position? 我想要实现的是: 目标

提前感谢=)

您可以删除现有的 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