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

Seaborn中折线图搭配柱状图时按折线数值排序的实现咨询

实现方法

核心思路是先将数据集按折线对应的B列降序重排,再强制指定柱状图的横轴顺序和排序后的结果一致,避免两者错位,修改后代码如下:

  1. 先对原DataFrame按B列降序排序:
af_sorted = af.sort_values(by='B', ascending=False, ignore_index=True)
  1. 修改绘图代码,显式指定两个图的x轴对应排序后的数据,且给柱状图传入order参数固定横轴顺序:
import matplotlib.pyplot as plt
import seaborn as sns

fig, ax1 = plt.subplots(1,1,figsize=(6,4))
# 折线图使用排序后的数据,显式指定x和y对应列
sns.lineplot(x=af_sorted['A'], y=af_sorted['B'], marker='o', ax=ax1)
ax2 = ax1.twinx()
# 用order参数强制柱状图横轴按排序后的A列值排列
sns.barplot(data=af_sorted, x='A', y='C', alpha=0.5, ax=ax2, order=af_sorted['A'].astype(str))
plt.show()

注意点

  • 不要直接给lineplot传入单列Series,否则会默认按原DataFrame的索引绘制,容易和柱状图横轴错位
  • order参数里把A列转成字符串是为了避免seaborn自动将数值类型的A按升序重排,破坏我们指定的顺序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:06:03