当小时和分钟位于不同的 pandas 列时,如何绘制它们?
How do I plot hours and minutes when they are in different pandas columns?
我有一个 pandas' 数据框,例如:
hour minute cnt
0 0 904890
0 30 880374
1 0 848198
1 30 816488
2 0 791761
我想在 matplotlib 中使用 minute
作为次刻度,并使用 hour
作为主要刻度来绘制 cnt
。我尝试了几件事,但没有奏效。这是一个:
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 ...
谢谢。
我得到这个结果:
使用此代码:
# 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'
) 上绘制您的数据,最后我调整主轴和副轴格式、刻度、限制和标签(最终标签旋转)。
我有一个 pandas' 数据框,例如:
hour minute cnt
0 0 904890
0 30 880374
1 0 848198
1 30 816488
2 0 791761
我想在 matplotlib 中使用 minute
作为次刻度,并使用 hour
作为主要刻度来绘制 cnt
。我尝试了几件事,但没有奏效。这是一个:
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 ...
谢谢。
我得到这个结果:
使用此代码:
# 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'
) 上绘制您的数据,最后我调整主轴和副轴格式、刻度、限制和标签(最终标签旋转)。