matplotlib中日期时间轴的格式

2024-10-01 17:37:40 发布

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

我正在尝试将图形的x轴更改为适当的datetime。 我试着回答:Changing the formatting of a datetime axis in matplotlib但是我的代码似乎有问题

这是原始图表。 enter image description here 使用此代码:

csv = 'Hydro.csv'

df = pd.read_csv(csv, header=None, names=['time', 'mwp', 'ppld', 'mwd', 'shts', 'tides', 'tan B', 'Lo', 'E', 'wind speed', 'wind gust', 'wind direction'])
fig = plt.figure(tight_layout=False)
gs = gridspec.GridSpec(5, 1)

ax1 = fig.add_subplot(gs[0, :])
ax1.plot(df['time'], df['ppld'], label = 'Peak Wave Period', linewidth = 1, color ='k')
ax1.set_ylabel ('Tp[s]', size = 10)

ax1.grid(True, ls='--')
plt.setp(ax1.get_xticklabels(), visible=True, rotation = 90)

当我开始调整刻度时,它无法正确绘制图形: enter image description here

csv = 'Hydro.csv'

df = pd.read_csv(csv, header=None, names=['time', 'mwp', 'ppld', 'mwd', 'shts', 'tides', 'tan B', 'Lo', 'E', 'wind speed', 'wind gust', 'wind direction'])
fig = plt.figure(tight_layout=False)
gs = gridspec.GridSpec(5, 1)

ax1 = fig.add_subplot(gs[0, :])
ax1.plot(df['time'], df['ppld'], label = 'Peak Wave Period', linewidth = 1, color ='k')
ax1.set_ylabel ('Tp[s]', size = 10)
ax1.grid(True, ls='--')

ax1.xaxis_date()
ax1.set_xticks(df['time'])
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%M:%D"))
ax1.xaxis.set_minor_formatter(mdates.DateFormatter("%H"))
_=plt.xticks(rotation=45)  


plt.show()

我希望它显示6小时间隔和日期/月


Tags: csv代码gstrue图形dfdatetimetime
1条回答
网友
1楼 · 发布于 2024-10-01 17:37:40

正如评论中所建议的,我必须先转换成日期

csv = 'Hydro.csv'

df = pd.read_csv(csv, header=None, names=['time', 'mwp', 'ppld', 'mwd', 'shts', 'tides', 'tan B', 'Lo', 'E', 'wind speed', 'wind gust', 'wind direction'])
xp = [datetime.strptime(d, "%d/%m/%Y %H:%M:%S") for d in df['time']]

xs = mdates.date2num(xp)
date = mdates.DateFormatter ("%d/%m/%Y\n%H:%M:%S")

fig = plt.figure(tight_layout=False)
gs = gridspec.GridSpec(5, 1)

ax1 = fig.add_subplot(gs[0, :])
ax1.xaxis.set_major_formatter(date)
ax1.xaxis.set_ticks_position('top')
ax1.set_ylabel ('$T_p[s]$', size = 10)
ax1.grid(True, ls=' ')
ax1.plot(xs, df['ppld'], linewidth = 1, color = 'k')

相关问题 更多 >

    热门问题