在Matplotlib x轴标签格式的日期时间

问题描述 投票:-1回答:1

我现在有一个dateframe,看起来像下面这样:

enter image description here

如果我打印出来的数据类型,时间是datetime.date和价格numpy.float64。当我尝试这个使用下面的代码来绘制,我得到下面的情节:

from matplotlib import dates
import matplotlib.pyplot as plt

plt.figure(figsize=(20, 10))
plt.plot(df['time'], df['price']*100, color='royalblue', marker='o', markersize=8, linewidth=3.5)

enter image description here

我很困惑,为什么x轴搞砸了,为什么,因为他们是日期被格式化。理想的情况是我只是想在数据帧的time列中所指定的日期。其他一些职位#1建议DateFormatter,所以我尝试添加以下行:plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%Y-%m-%d'))。但是,我得到的错误“名单”对象有没有属性“DateFormatter”。很想对如何修复时间在x轴格式的建议(理想情况下,应该只有对应于指定时间5个滴答)。谢谢!

python datetime matplotlib datetime-format axis-labels
1个回答
0
投票

用大熊猫.plot()方法来利用大熊猫格式化能力。该方法有多种,是值得探讨here选项。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'Price': np.random.randint(20, 60, size=10),
                   'Change': np.random.randint(0, 10, size=10),
                   'Date': pd.date_range('2019-01-01', periods=10, freq='D')})

df.plot(x='Date', 
        y=['Price', 'Change'], 
        marker='o',
        markersize=8, 
        linewidth=2.0)

enter image description here

df.plot(x='Date', 
        y=['Price', 'Change'], 
        marker='o',
        markersize=8, 
        linewidth=2.0,
        color=['green', 'red'],
        subplots=True)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.