【问题标题】:Order the x axis in seaborn for two columns在seaborn中为两列订购x轴
【发布时间】:2020-06-15 13:33:44
【问题描述】:

我想用 seaborn lineplot 绘制一个数据框,其结构如下:

A  Year Month diff
Der 2019 1    3
Der 2019 2    4
Die 2019 1    1
Die 2019 2    1

现在我正在尝试:

sns.lineplot(x= ['Year', 'Month'], y='diff', hue='A', ci=None, data = df)
plt.show()

如何获得从 2019 1 开始并按月份顺序排列的时间线图,而没有时间列?

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

    您可以根据年份和月份创建一个新的date 列,并将日期设置为 1:

    from datetime import date
    import matplotlib.dates as mdates
    
    df['date'] = df.apply(lambda row: date(row['Year'], row['Month'], 1), axis=1)
    ax = sns.lineplot(x='date', y='diff', hue='A', ci=None, data=df)
    
    # To only show x-axis ticks once per month:
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 2018-07-18
      • 2020-09-04
      • 2018-04-05
      相关资源
      最近更新 更多