You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Seaborn柱状图中设置xlim且避免柱状图左移?

解决Seaborn柱状图设置x轴范围后左移的问题

我用Seaborn制作了展示一年中指定日期出生人数的柱状图(图a),希望将x轴范围设为(0,365)以显示全年,但调用ax.set_xlim(0,365)后,柱状图仅发生左移(图b),并未按日期实际数值在0-365范围内分布。

柱状图左移问题示意图

原代码

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

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

# 绘图
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')

问题原因

seaborn.barplot默认将x轴的每个类别按顺序索引(0、1、2...)排列,而非使用day列的实际数值作为x坐标。设置xlim(0,365)只是扩大了坐标轴范围,但柱子仍按索引位置摆放,因此出现左移现象。

解决方案

方案1:改用Matplotlib原生bar函数

直接基于day的实际数值绘制柱子,让x坐标与日期值一一对应:

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

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

# 绘图
f, axes = plt.subplots(4, 4, figsize=(12,12))
ax = axes[0,0]
ax.bar(df['day'], df['born'], 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')

方案2:补全全年日期数据后使用Seaborn barplot

通过补全1-365所有日期的缺失数据,让barplot的x类别对应实际日期:

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

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

# 补全全年日期,缺失日期的出生人数设为0
full_days = pd.DataFrame({'day': np.arange(1,366)})
df_full = pd.merge(full_days, df, on='day', how='left').fillna(0)

# 绘图
f, axes = plt.subplots(4,4, figsize=(12,12))
ax = sns.barplot(x='day', y='born', data=df_full, 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(-1, 366)  # 轻微左移避免首柱被截断
ax.set_title('SE Africa')

内容的提问来源于stack exchange,提问作者Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 18:20:33