繁体   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