簡體   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