【问题标题】:Python plot shows numbers instead of Dates on x axisPython 绘图在 x 轴上显示数字而不是日期
【发布时间】:2020-03-11 20:42:24
【问题描述】:

我正在尝试绘制股票图表。 我的 DataFrame 结构如下所示:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 503 entries, 0 to 506
Data columns (total 6 columns):
Date      503 non-null object
Open      503 non-null float64
High      503 non-null float64
Low       503 non-null float64
Close     503 non-null float64
Volume    503 non-null float64
dtypes: float64(5), object(1)
memory usage: 27.5+ KB

当我尝试使用 Close-column 绘制数据时,我在 x 轴上得到了数字,但我想使用 3 个月的刻度绘制日期。我怎样才能做到这一点?

目前该情节的代码如下所示:

dax_data["Close"].plot(label = "Dax Close", figsize = (16,8), title = "Dax Prices")
plt.legend();

Here you can see the plot

【问题讨论】:

    标签: python pandas date plot


    【解决方案1】:

    这是因为“DataFrame.plot()”默认使用数据框索引作为 x 值。 你应该这样做:

    dax_data.plot(x = 'Date', y = 'Close', label = "Dax Close", figsize = (16,8), title = "Dax Prices")
    

    并且有 3 个月的滴答声:

    import matplotlib.dates as mdates
    
    ### Your code to get dax_data
    
    ax = dax_data.plot(x = 'Date', y = 'Close', label = "Dax Close", figsize = (16,8), title = "Dax Prices")
    ax.xaxis.set_major_locator(mdates.MonthLocator(interval = 3)) # to display ticks every 3 months
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%m-%Y")) # to set how dates are displayed
    plt.legend()
    

    【讨论】:

    • 太棒了。谢谢你。这正是我想要的。
    猜你喜欢
    • 2021-08-21
    • 2016-02-16
    • 2015-06-19
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多