繁体   English   中英

如何格式化 Pandas / Matplotlib 图形,以便 x 轴刻度只有小时和分钟?

[英]How to format Pandas / Matplotlib graph so the x-axis ticks are ONLY hours and minutes?

我正在尝试根据 csv 文件中的时间数据绘制温度。

我的目标是有一个图表来显示每天的温度数据。

我的问题是 x 轴:我想统一显示时间,并且只以小时和分钟为单位,间隔 15 分钟,例如: 00:00 , 00:15 , 00:30

csv 被加载到一个 Pandas 数据帧中,在那里我根据它是哪一天过滤要显示的数据,在代码中我只想要当月第 18 天的温度数据。

这是我正在加载的 csv 数据:

date,temp,humid
2020-10-17 23:50:02,20.57,87.5
2020-10-17 23:55:02,20.57,87.5
2020-10-18 00:00:02,20.55,87.31
2020-10-18 00:05:02,20.54,87.17
2020-10-18 00:10:02,20.54,87.16
2020-10-18 00:15:02,20.52,87.22
2020-10-18 00:20:02,20.5,87.24
2020-10-18 00:25:02,20.5,87.24

这是制作图形的python代码:

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

df = pd.read_csv("saveData2020.csv")

#make new columns in dataframe so data can be filtered
df["New_Date"] = pd.to_datetime(df["date"]).dt.date
df["New_Time"] = pd.to_datetime(df["date"]).dt.time
df["New_hrs"] = pd.to_datetime(df["date"]).dt.hour
df["New_mins"] = pd.to_datetime(df["date"]).dt.minute
df["day"] = pd.DatetimeIndex(df['New_Date']).day

#filter the data to be only day 18
ndf = df[df["day"]==18]

#display dataframe in console
pd.set_option('display.max_rows', ndf.shape[0]+1)
print(ndf.head(10))

#plot a graph
ndf.plot(kind='line',x='New_Time',y='temp',color='red')

#edit graph to be sexy
plt.setp(plt.gca().xaxis.get_majorticklabels(),'rotation', 30)
plt.xlabel("time")
plt.ylabel("temp in C")

#show graph with the sexiness edits
plt.show()

这是我得到的图表:

绘图窗口

回答

首先,您必须使用以下命令将"New Time" (您的 x 轴)从strdatetime类型:

ndf["New_Time"] = pd.to_datetime(ndf["New_Time"], format = "%H:%M:%S")

然后,您可以在显示绘图之前简单地添加这行代码(并导入正确的 matplotlib 库, matplotlib.dates as md )来告诉 matplotlib 您只需要几小时和几分钟:

plt.gca().xaxis.set_major_formatter(md.DateFormatter('%H:%M'))

这行代码用于修复滴答声的 15 分钟跨度:

plt.gca().xaxis.set_major_locator(md.MinuteLocator(byminute = [0, 15, 30, 45]))

有关 x 轴时间格式的更多信息,您可以查看此答案

代码

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

df = pd.read_csv("saveData2020.csv")


#make new columns in dataframe so data can be filtered
df["New_Date"] = pd.to_datetime(df["date"]).dt.date
df["New_Time"] = pd.to_datetime(df["date"]).dt.time
df["New_hrs"] = pd.to_datetime(df["date"]).dt.hour
df["New_mins"] = pd.to_datetime(df["date"]).dt.minute
df["day"] = pd.DatetimeIndex(df['New_Date']).day

#filter the data to be only day 18
ndf = df[df["day"]==18]
ndf["New_Time"] = pd.to_datetime(ndf["New_Time"], format = "%H:%M:%S")

#display dataframe in console
pd.set_option('display.max_rows', ndf.shape[0]+1)
print(ndf.head(10))

#plot a graph
ndf.plot(kind='line',x='New_Time',y='temp',color='red')

#edit graph to be sexy
plt.setp(plt.gca().xaxis.get_majorticklabels(),'rotation', 30)
plt.xlabel("time")
plt.ylabel("temp in C")

plt.gca().xaxis.set_major_locator(md.MinuteLocator(byminute = [0, 15, 30, 45]))
plt.gca().xaxis.set_major_formatter(md.DateFormatter('%H:%M'))

#show graph with the sexiness edits
plt.show()

阴谋

在此处输入图片说明

笔记

如果您不需要"New_Date""New_Time""New hrs""New_mins""day"列用于绘图以外的其他目的,您可以使用上述代码的较短版本,去掉这些列并应用直接在"date"列上过滤"date"如下所示:

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

df = pd.read_csv("saveData2020.csv")

# convert date from string to datetime
df["date"] = pd.to_datetime(df["date"], format = "%Y-%m-%d %H:%M:%S")

#filter the data to be only day 18
ndf = df[df["date"].dt.day == 18]

#display dataframe in console
pd.set_option('display.max_rows', ndf.shape[0]+1)
print(ndf.head(10))

#plot a graph
ndf.plot(kind='line',x='date',y='temp',color='red')

#edit graph to be sexy
plt.setp(plt.gca().xaxis.get_majorticklabels(),'rotation', 30)
plt.xlabel("time")
plt.ylabel("temp in C")

plt.gca().xaxis.set_major_locator(md.MinuteLocator(byminute = [0, 15, 30, 45]))
plt.gca().xaxis.set_major_formatter(md.DateFormatter('%H:%M'))

#show graph with the sexiness edits
plt.show()

此代码将重现与之前完全相同的图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM