【问题标题】:python matplotlib - How to make sure x axis values to be the same of the source datapython matplotlib - 如何确保x轴值与源数据相同
【发布时间】:2020-09-23 03:35:28
【问题描述】:

我正在尝试在 matplotlib 上进行一些绘图。这是我的数据df

     datadate       loss_CF
0  2020-03-31  14744.417859
1  2020-06-30  18443.540626
2  2020-09-30  21902.934212
3  2020-12-31  24743.491101
4  2021-03-31  22532.267947
5  2021-06-30  21835.597756
6  2021-09-30  21607.682299
7  2021-12-31  22898.842686
8  2022-03-31  21513.368257
9  2022-06-30  20412.728656
10 2022-09-30  19598.518147
11 2022-12-31  18220.543880

这是我绘制它的代码:

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

#date = df['datadate'].dt.strftime('%y-%b')
fig, ax = plt.subplots()
y_formatter = ticker.StrMethodFormatter('${x:,.0f}')
x_formatter = DateFormatter('%b-%y')
ax.yaxis.set_major_formatter(y_formatter)
ax.xaxis.set_major_formatter(x_formatter)
plt.plot(df['datadate'], df['loss_CF'])
plt.show()

这是我得到的图:

有没有办法将 x 轴值更改为 df 中的 datadate?换句话说,我希望它们都是季度末月份,而不是一月、五月等。例如,对应于第一个数据点的第一个刻度应该是 Mar-20。我怎样才能做到这一点?我认为ax.set_xticksax.set_xticklabels 可能是答案,但在尝试了很长时间后,我仍然无法得到我想要的理想情节。

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    由于您的数据不会太长,您可以针对字符串进行绘图:

    fig, ax = plt.subplots(figsize=(10,6))
    
    plt.plot(df['datadate'].dt.strftime('%b-%y'), df['loss_CF'])
    plt.show()
    

    输出:

    另外,你可以试试 pandas 的绘图功能:

    fig, ax = plt.subplots(figsize=(10,6))
    x_formatter = DateFormatter('%b-%y')
    (df.assign(date=df.datadate.dt.to_period('Q'))
       .plot(x='date',y='loss_CF',ax=ax)
    )
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 2019-06-02
      • 2021-09-09
      相关资源
      最近更新 更多