我有以下代码绘制了预期的输出:
import matplotlib.pyplot as plt
import csv
import datetime
import matplotlib.dates as mdates
import re
Time = []
station12SRV = []
station18SRV = []
with open('Book2.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
datetime_format = '%d/%m/%Y %H:%M'
date_time_data = datetime.datetime.strptime(row[0],datetime_format)
Time.append(date_time_data)
station12SRV.append(float(row[1]))
station18SRV.append(float(row[2]))
plt.plot(Time,station12SRV, label='Tracker Station 12')
plt.plot(Time,station18SRV, label='Tracker Station 18')
plt.xlabel('Date & Time')
plt.ylabel('Pressure (Torr)')
plt.yscale('log')
#plt.title('SRV Plot vs Time')
plt.legend()
plt.savefig('trackers_srv.pdf')
#plt.show()
但是,在绘图中,x轴未同时显示日期和时间,而仅显示时间:
如何在x轴上同时显示日期和时间?谢谢。
答案 0 :(得分:1)
获取在x轴上格式化的日期和时间的最简单方法之一是将数据放入Pandas数据框中并使用df.plot()
:
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(3)
import pandas as pd
# Generate sample data
Time = pd.date_range('3/1/19 12:00 AM', '3/3/19 12:00 AM', freq='1H')
n = len(Time)
df = pd.DataFrame({'Tracker Station 12': np.random.rand(n), 'Tracker Station 18': 1+np.random.rand(n), 'Time': Time})
df = df.set_index('Time')
df.plot()
plt.ylabel('Pressure (Torr)')
plt.yscale('log')