如何使用Python的MatPlotLib根据时间安排绘图?

2024-07-04 07:46:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组datetime数据,格式为2020-10-02 18:48:21的pandas系列。我只想根据另一个数据帧中的分数值绘制该日期时间内包含的时间

下面是我使用以下代码得到的最接近的结果:

Closest scatter plot

def timePop(oneDate, oneScore, twoDate, twoScore, title):
    myFmt = "%H:%M:%S"

    for index, value in oneDate.iteritems():
        new_time = datetime.fromtimestamp(oneDate[index]).time()
        oneDate[index] = datetime.strptime(str(new_time), myFmt)


    for index, value in twoDate.iteritems():
        new_time2 = datetime.fromtimestamp(twoDate[index]).time()
        twoDate[index] = datetime.strptime(str(new_time2), myFmt)


    fig, ax = pylt.subplots()
    ax.scatter(oneDate, oneScore, c='r', marker='*', label="Popular")
    ax.scatter(twoDate, twoScore, c='b', marker='o', label="Unpopular")
    pylt.xlabel('24 Hours')
    pylt.ylabel('Scores')
    pylt.xticks(rotation=45)
    # ax.format_xdata = mdates.DateFormatter(myFmt)
    # ax.set_xticks([0, 1, 2, 3, 4, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24])
    pylt.title('Time and Score Distribution of Posts in %s' % title)
    pylt.show()

我已经研究了StackOverflow上的各种可能的解决方案,以及文档,但运气不好。理想情况下,我希望x轴以1小时为增量。如果有人能帮忙,我将不胜感激


Tags: 数据innewdatetimeindextimetitle时间
1条回答
网友
1楼 · 发布于 2024-07-04 07:46:46

让我们看看:假设您有这样一个玩具示例:

import matplotlib.pyplot as plt
import datetime

dates = [datetime.date(2020,12,i) for i in range(1,24)]
num = [i for i in range(1,24)]

代表圣诞节之前的日子。 您只需提取列表中日期的^{}并绘制它们:

plt.plot([d.weekday() for d in dates],num,'.') # monday = 0

weekdays

本周从周一开始,周一表示为零。如果要获取带有日期名称的字符串,可以使用^{}格式化输出:

plt.plot([d.strftime("%A") for d in dates],num,'.')

weekday names

基本上,您可以按字符串对数据进行分组。这也意味着,任何字符串都足够了。我们可以利用这一点对白天进行如下分类:

dates2 = [datetime.datetime(2020,12,i,i,i,0) for i in range(1,24)]

def f(x):
    if (x > 4) and (x <= 8):
        return 'Early Morning'
    elif (x > 8) and (x <= 12 ):
        return 'Morning'
    elif (x > 12) and (x <= 16):
        return'Noon'
    elif (x > 16) and (x <= 20) :
        return 'Eve'
    elif (x > 20) and (x <= 24):
        return'Night'
    elif (x <= 4):
        return'Late Night'

plt.plot([f(d.hour) for d in dates2],num,'.')

首先,我们创建新的datetime.datetime类型的伪数据,而不仅仅是datetime.date。然后,我将一个具有类似于switch case结构的函数here转换为类别。 这和以前一样。我们立即创建一个新列表,从datetime对象中提取.hour,并将其提供给函数f,该函数对数据进行分类 times

相关问题 更多 >

    热门问题