Seaborn多列堆叠柱状图绘制问题:部分数据未显示求助
解决方案
一、修复Seaborn堆叠柱状图显示不全问题
Seaborn的barplot默认会在同一x轴位置重叠绘制柱子,而非堆叠,数值大的柱子会覆盖小的,这就是你看不到Contract、Definite的原因。要实现堆叠效果,需要手动指定每个柱子的bottom参数,即该柱子底部的高度为前面所有系列的累计值。
修改后的代码如下:
import matplotlib.pyplot as plt import seaborn as sns import matplotlib.ticker as tick # 自定义大数值格式化函数(适配你的需求) def reformat_large_tick_values(tick_val, pos): if tick_val >= 1000: return f'${tick_val/1000:,.0f}K' return f'${tick_val:,.0f}' plt.figure() sns.set_theme(context="notebook", style="darkgrid", palette="deep", font="sans-serif", rc={"figure.figsize": (20, 12)}) # 依次绘制每个系列,设置bottom为前面系列的累计和 ax = sns.barplot(data=graph_df, x="Month", y="Contract", color="green") ax = sns.barplot(data=graph_df, x="Month", y="Definite", color="lightgreen", bottom=graph_df["Contract"]) ax = sns.barplot(data=graph_df, x="Month", y="T1", color="blue", bottom=graph_df["Contract"] + graph_df["Definite"]) ax = sns.barplot(data=graph_df, x="Month", y="T2", color="lightblue", bottom=graph_df["Contract"] + graph_df["Definite"] + graph_df["T1"]) ax = sns.barplot(data=graph_df, x="Month", y="CXLD", color="red", bottom=graph_df["Contract"] + graph_df["Definite"] + graph_df["T1"] + graph_df["T2"]) # 设置Y轴格式 ax.yaxis.set_major_formatter(tick.FuncFormatter(reformat_large_tick_values)) # 正确设置Y轴标签(注意是调用方法,不是直接赋值) ax.set_ylabel("Total $'s") plt.show()
二、修复Matplotlib堆叠图的Y轴格式与标签问题
如果你更倾向于用Matplotlib绘制堆叠图,只需调整Y轴格式化器和标签设置即可:
示例代码:
import matplotlib.pyplot as plt import matplotlib.ticker as tick fig, ax = plt.subplots(figsize=(20,12)) # 绘制堆叠柱状图 ax.bar(graph_df["Month"], graph_df["Contract"], color="green", label="Contract") ax.bar(graph_df["Month"], graph_df["Definite"], color="lightgreen", bottom=graph_df["Contract"], label="Definite") ax.bar(graph_df["Month"], graph_df["T1"], color="blue", bottom=graph_df["Contract"]+graph_df["Definite"], label="T1") ax.bar(graph_df["Month"], graph_df["T2"], color="lightblue", bottom=graph_df["Contract"]+graph_df["Definite"]+graph_df["T1"], label="T2") ax.bar(graph_df["Month"], graph_df["CXLD"], color="red", bottom=graph_df["Contract"]+graph_df["Definite"]+graph_df["T1"]+graph_df["T2"], label="CXLD") # 方法1:用StrMethodFormatter快速设置美元格式 ax.yaxis.set_major_formatter(tick.StrMethodFormatter("${x:,.0f}")) # 也可以用你自定义的格式化函数 # ax.yaxis.set_major_formatter(tick.FuncFormatter(reformat_large_tick_values)) # 设置Y轴标签 ax.set_ylabel("Total $'s") # 添加图例 ax.legend() plt.show()
关键注意点:
- 你原代码中
plt.ylabel = "Total Rent"是错误写法,应该调用ax.set_ylabel()或plt.ylabel()函数,直接赋值无法生效。 - 美元格式化可以用
StrMethodFormatter简化代码,"${x:,.0f}"会自动添加美元符号并处理千位分隔;如果需要显示为千位缩写(如$1.3M),可以用自定义函数实现。
内容的提问来源于stack exchange,提问作者Rob Brooks
相关产品推荐
相关产品推荐

