【问题标题】:Formatting time on a plot in Python在 Python 中的绘图上格式化时间
【发布时间】:2015-07-24 00:06:23
【问题描述】:

我有以下代码,想知道如何将时间格式化为 12 小时格式。例如0:00, 3:30, 10:00 等到目前为止,y 轴读取 00:00:00, 00:01:00, 00:02:00 等等。 csv中的数据格式如下,0:00、1:00、2:00等

如何将 y 轴格式化为我需要的格式?

这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import datetime

data = pd.read_csv('data.csv', sep=',', header=None)

ints = data[data[1]=='INT']
exts = data[data[1]=='EXT']

int_times = [datetime.datetime.time(datetime.datetime.strptime(t, '%H:%M')) 
             for t in ints[4]]
ext_times = [datetime.datetime.time(datetime.datetime.strptime(t, '%H:%M')) 
             for t in exts[4]]
int_dist = [d for d in ints[3]]
ext_dist = [d for d in exts[3]]

axis_times = ['0:00','01:00', '02:00', '03:00', '04:00', '05:00','06:00',
              '07:00','08:00','09:00','10:00','11:00','12:00']

fig, ax = plt.subplots()
ax.scatter(int_dist, int_times, c='red', s=50)
ax.scatter(ext_dist, ext_times, c='blue', s=50)

plt.yticks( axis_times, size='small')

plt.legend(['INT', 'EXT'], loc=4)
plt.xlabel('Distance')
plt.ylabel('Time')

plt.show()

这是图表显示的图像:

【问题讨论】:

    标签: python datetime pandas matplotlib


    【解决方案1】:

    使用DateFormatter:

    import matplotlib.dates as md
    yfmt = md.DateFormatter('%H:%M')
    ax.yaxis.set_major_formatter(yfmt)
    

    【讨论】:

    • 你从哪里得到 ymft 和 md?
    • 感谢 @ubuntu 将 matplotlib 包含为 md; ymft 是我声明的变量
    • @hankharrison 我相信yfmty 轴格式 的缩写,mdm = matplotlibd 的缩写= 日期
    • 该代码似乎不起作用,我该把它放在哪里?
    • 你能更新代码以显示你包含它的位置吗?
    猜你喜欢
    • 2021-04-03
    • 2012-06-24
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多