簡體   English   中英

如何在 seaborn barplot 中設置 xlim?

[英]How to set xlim in seaborn barplot?

我為一年中的特定日子和這一天出生的人數創建了一個條形圖(圖 a)。 我想將 seaborn 條形圖中的 x 軸設置為xlim = (0,365)以顯示全年。 但是,一旦我使用ax.set_xlim(0,365) ,條形圖 plot 就會簡單地向左移動(圖 b)。

圖片

這是代碼:

#data
df = pd.DataFrame()
df['day'] = np.arange(41,200)
df['born'] = np.random.randn(159)*100

#plot
f, axes = plt.subplots(4, 4, figsize = (12,12))
ax = sns.barplot(df.day, df.born, data = df, hue = df.time, ax = axes[0,0], color = 'skyblue')
ax.get_xaxis().set_label_text('')
ax.set_xticklabels('')
ax.set_yscale('log')
ax.set_ylim(0,10e3)
ax.set_xlim(0,366)
ax.set_title('SE Africa')

如何在不向左移動條形的情況下將 x 軸限制設置為第 0 天和第 365 天?

IIUC,鑒於數據的性質,預期的 output 很難直接獲得,因為根據seaborn.barplot的文檔:

此 function 始終將其中一個變量視為分類變量,並在相關軸上的順序位置 (0、1、... n) 繪制數據,即使數據具有數字或日期類型也是如此。

這意味着 function seaborn.barplot根據x中的數據(此處為df.day )創建類別,並且它們鏈接到從 0 開始的整數。

因此,這意味着即使我們有第 41 天以后的數據,seaborn 也會引用x = 0的起始類別,這讓我們很難在 function 調用后調整 x 軸的下限。

以下代碼和對應的 plot 闡明了我上面解釋的內容:

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

# data
rng = np.random.default_rng(101)
day = np.arange(41,200)
born = rng.integers(low=0, high=10e4, size=200-41)

df = pd.DataFrame({"day":day, "born":born})

# plot
f, ax = plt.subplots(figsize=(4, 4))

sns.barplot(data=df, x='day', y='born', ax=ax, color='b')
ax.set_xlim(0,365)
ax.set_xticks(ticks=np.arange(0, 365, 30), labels=np.arange(0, 365, 30))
ax.set_yscale('log')
ax.set_title('SE Africa')
plt.tight_layout()
plt.show()

在此處輸入圖像描述

我建議使用matplotlib.axes.Axes.bar來解決這個問題,盡管與sns.barplot(..., hue=..., ...)相比,處理 colors 的條形並不簡單:

# plot
f, ax = plt.subplots(figsize=(4, 4))

ax.bar(x=df.day, height=df.born) # instead of sns.barplot
ax.get_xaxis().set_label_text('')
ax.set_xlim(0,365)
ax.set_yscale('log')
ax.set_title('SE Africa')
plt.tight_layout()
plt.show()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM