2

我有一个熊猫的数据框,例如:

 hour   minute     cnt
    0        0  904890
    0       30  880374
    1        0  848198
    1       30  816488
    2        0  791761

我想在 matplotlib 中cnt使用minute作为次要刻度和主要刻度进行绘图。hour我尝试了几件事,但没有奏效。这是一个:

fig, ax = plt.subplots(figsize=(8,5))
df.plot(kind='line', y='cnt', ax=ax)
ax.set_xticks(df['minute'])
ax.set_xticklabels(df['minute'])

我希望我的 x 轴看起来像

|---+---+---+---+---+---+---+---|
0   15  30  45  0   30  45  0   15
0               1           2   ...

谢谢。

4

1 回答 1

1

我得到这个结果:

在此处输入图像描述

使用此代码:

# 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') 上,最后我调整主轴和次轴格式、刻度、限制和标签(最终标签旋转)。

于 2020-06-25T22:05:25.947 回答