seaborn/matplotlib 中的条形图和线图

社会演员多 python 206

原文标题Barplot and line plot in seaborn/matplotlib

我有一个熊猫df,如下所示:

Date            Col1       Col2
2022-01-01      5          10000
2022-02-01      7          65000
2022-03-01      10         9500

我想创建一个图,使得xaxisDateCol1是条形图,Col2是线图。我怎样才能在 python 中做到这一点?打开试试 seaborn 或 matplotlib。Date是一个pd.datetime对象。谢谢!

原文链接:https://stackoverflow.com//questions/71508057/barplot-and-line-plot-in-seaborn-matplotlib

回复

我来回复
  • tdy的头像
    tdy 评论

    由于这两个比例有很大不同,所以创建一个辅助 y 轴。

    由于条形图是分类图,seaborn 将x日期转换为序号刻度。这意味着 matplotlib 日期格式化程序将不再适用于它们,因此最好预先格式化日期字符串,例如,dt.datedt.strftime

    此外,由于 seaborn 将 x 轴更改为序号刻度,因此使用 apointplot 创建线条是最简单的(但如果您真的想使用 alineplot,请重置索引并将x设置为数字范围)。

    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx() # secondary y-axis
    
    df['Date'] = df['Date'].dt.date # or dt.strftime('%Y-%m-%d')
    
    sns.barplot(x='Date', y='Col1', data=df, ax=ax1) # on primary ax1
    sns.pointplot(x='Date', y='Col2', color='#333', data=df, ax=ax2) # on secondary ax2
    
    # sns.lineplot(x='index', y='Col2', color='#333', data=df.reset_index(), ax=ax2)
    

    2年前 0条评论