我得到这个结果:
使用此代码:
# import
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as md
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
# read data and generate time column
df = pd.read_csv('data.csv')
df['time'] = (df['hour'].astype(str) + ':' + df['minute'].astype(str)).apply(lambda x: pd.to_datetime(str(x), format = '%H:%M'))
# prepare figure object and axes
fig = plt.figure(figsize = (8, 6))
minutes = host_subplot(111, axes_class = AA.Axes, figure = fig)
plt.subplots_adjust(bottom = 0.1)
hours = minutes.twiny()
# move at the bottom the secondary axis
offset = -20
new_fixed_axis = hours.get_grid_helper().new_fixed_axis
hours.axis['bottom'] = new_fixed_axis(loc = 'bottom',
axes = hours,
offset = (0, offset))
hours.axis['bottom'].toggle(all = True)
# plot
minutes.plot(df['time'], df['cnt'])
# adjust minutes axis format, ticks and labels
minutes.xaxis.set_major_locator(md.MinuteLocator(byminute = range(0, 60, 15)))
minutes.xaxis.set_major_formatter(md.DateFormatter('%M'))
plt.setp(minutes.xaxis.get_majorticklabels(), rotation = 0)
minutes.set_xlim([df['time'].iloc[0], df['time'].iloc[-1]])
# adjust hours axis format, ticks and labels
hours.xaxis.set_major_locator(md.HourLocator(interval = 1))
hours.xaxis.set_major_formatter(md.DateFormatter('%H'))
hours.set_xlim([df['time'].iloc[0], df['time'].iloc[-1]])
# show the plot
plt.show()
首先,我生成一个datetime
列('time'
),以便合并'hour'
列'minute'
。然后我准备了一个带有两个轴的图形:主要用于分钟,次要用于小时。然后我继续操作辅助轴(将其移动到底部)。然后我将您的数据绘制在主轴 ( 'minutes'
) 上,最后我调整主轴和次轴格式、刻度、限制和标签(最终标签旋转)。