【问题标题】:Seaborn, matplotlib not recognizing time as timeSeaborn,matplotlib 不承认时间为时间
【发布时间】:2021-03-27 20:02:16
【问题描述】:

我的 seaborn/matplotib 图没有将时间识别为时间。

     temp         t           d
0    39.9  00:24:23  03-21-2021
1    39.9  00:28:32  03-21-2021
2    39.4  00:32:41  03-21-2021
3    39.2  00:36:48  03-21-2021
4    38.8  00:40:57  03-21-2021
..    ...       ...         ...
240  59.0  17:02:14  03-21-2021
241  58.5  17:06:23  03-21-2021
242  58.5  17:10:31  03-21-2021
243  58.5  17:14:40  03-21-2021
244  58.1  17:18:49  03-21-2021

我正在尝试将我的 x-ticks 汇总到小时

我的研究使我相信我的时间数据没有以 matplotlib 识别为时间的方式格式化。

这是生成绘图的代码区域:

#panda datafram is 'values'

g=sns.lineplot(x='t', y='temp', data=values,color="darkblue")


plt.ylim(values['temp'].min()-1, values['temp'].max()+1)
plt.xticks(rotation=90)
# compensate for axis labels getting clipped off
plt.subplots_adjust(bottom=0.15, left=0.15)

g.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))



g.xaxis.set_major_locator(mdates.HourLocator(interval = 400))
g.set(xlabel='Time', ylabel='Temperature')

#create unique filename based on time
filename= "Graph-" +str(dt.datetime.now().hour)+"-"+str(dt.datetime.now().minute)+".png"

plt.savefig(filename)

如果在我的图中看不清我的 X 轴,那么如果你看一下我的数据框,时间数据就会很明显,时间都是一团糟(17、9、1)。

我可以以不同的格式保存我的时间数据,或者我需要为 seaborn/matplotlib 重新格式化我的时间数据????

【问题讨论】:

  • 请改进您的代码 sn-p 并提供MCVE
  • values.t.dtype 的输出是什么?
  • 这能回答你的问题吗? how to get ticks every hour?
  • @tdy 输出是'object'
  • @albert - thx 但不,问题是我的时间数据不是日期时间对象,下面的答案解决了它

标签: python pandas matplotlib seaborn


【解决方案1】:

由于values.t 当前类型为object,因此在调用sns.lineplot() 之前将其转换为to_datetime()

values.t = pd.to_datetime(values.t)
g = sns.lineplot(x='t', y='temp', data=values, color='darkblue')

(您可以通过检查values.t.dtype 是否是某种datetime 而不是object 来验证转换。)

【讨论】:

  • 完美,非常完美 - 非常感谢@tdy
  • 没问题,可以点击左边的对勾标记为已解决
【解决方案2】:

在读取 csv 文件时,您可以将包含字符串格式时间戳的列的名称传递给 parse_dates argument。因此,重要的一行是:

df = pd.read_csv(data, sep='\s+', parse_dates=['t'])

我使用您的数据 sn-p 创建了一些跨越几个小时的示例数据,并基于 this SO answer 构建了一些代码。

我的代码 sn-p 如下所示:

import io

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


data_string = """
temp  t         d
39.9  00:24:23  03-21-2021
39.9  00:28:32  03-21-2021
39.4  00:32:41  03-21-2021
39.2  00:36:48  03-21-2021
38.8  00:40:57  03-21-2021
39.9  00:50:23  03-21-2021
39.9  01:28:32  03-21-2021
39.4  01:32:41  03-21-2021
39.2  01:36:48  03-21-2021
38.8  01:40:57  03-21-2021
39.9  01:50:23  03-21-2021
39.9  02:24:23  03-21-2021
39.9  02:28:32  03-21-2021
39.4  02:32:41  03-21-2021
39.2  02:36:48  03-21-2021
38.8  02:40:57  03-21-2021
39.9  02:50:23  03-21-2021
39.9  03:28:32  03-21-2021
39.4  03:32:41  03-21-2021
39.2  03:36:48  03-21-2021
38.8  03:40:57  03-21-2021
39.9  03:50:23  03-21-2021
39.9  04:24:23  03-21-2021
39.9  04:28:32  03-21-2021
39.4  04:32:41  03-21-2021
39.2  04:36:48  03-21-2021
38.8  04:40:57  03-21-2021
39.9  04:50:23  03-21-2021
39.9  05:28:32  03-21-2021
39.4  05:32:41  03-21-2021
39.2  05:36:48  03-21-2021
38.8  05:40:57  03-21-2021
39.9  05:50:23  03-21-2021
"""

data = io.StringIO(data_string)
df = pd.read_csv(data, sep='\s+', parse_dates=['t'])

print(df)


hours = mdates.HourLocator(interval=1)
h_fmt = mdates.DateFormatter('%H:%M:%S')

fig, ax = plt.subplots()

ax.plot(df['t'], df['temp'])

ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)

fig.autofmt_xdate()

plt.show()

将生成以下图:

【讨论】:

    【解决方案3】:

    这是另一种方法。合并您的日期和时间列并将它们转换为日期时间对象列,然后使用 matplotlib.dates.date2num() 将日期时间转换为可用于 x 轴的数值:

    from matplotlib import pyplot as plt
    import pandas as pd
    from matplotlib import dates as mdates
    import datetime
    
    df = pd.read_csv('sample.csv')
    df['dt_string'] = df.d + ' ' + df.t
    df['dt'] = df['dt_string'].apply(lambda x: datetime.datetime.strptime(x, "%m-%d-%Y %H:%M:%S"))
    df['time_num'] = mdates.date2num(df.dt)
    print(df)
    
    #the first 5 rows of your dataframe:
       temp         t  ...                  dt      time_num
    0  39.9  00:24:23  ... 2021-03-21 00:24:23  18707.016933
    1  39.9  00:28:32  ... 2021-03-21 00:28:32  18707.019815
    2  39.4  00:32:41  ... 2021-03-21 00:32:41  18707.022697
    3  39.2  00:36:48  ... 2021-03-21 00:36:48  18707.025556
    4  38.8  00:40:57  ... 2021-03-21 00:40:57  18707.028438
    

    然后绘制如下:

    fig, ax = plt.subplots()
    ax.plot(df.time_num, df.temp)
    ax.set_xticks(df.dt)
    ax.set_xticklabels(df.dt)
    ax.set_xlabel('DateTime')
    ax.set_ylabel('Time')
    fig.autofmt_xdate()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2021-01-29
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多