创建一个折线图,x 轴为日期时间,y 轴为记录数

Create a line chart with datetime on x-axis and number of records on y-axis

我正在尝试创建一个折线图,其中 x 轴为日期时间数据,y 轴为每个月的记录数。

到目前为止,我已经将我需要的两列从原始数据框中复制到一个新列中,并更改了日期时间列的格式:

line_chart =frame[['index', 'Start Time and Date']].copy()
line_chart['Start Time and Date']=line_chart['Start Time and Date'].dt.to_period('M')

接下来,我尝试使用plotly创建图表:

import plotly.express as px
fig = px.line(line_chart, x='Start Time and Date', y='index')
fig.show()

但是我得到这个错误:Object of type Period is not JSON serializable

我也试过用matplotlib绘图:

x=line_chart['Start Time and Date']
y=line_chart['index']
plt.plot(x,y)
plt.gcf().autofmt_xdate()

plt.show()

但又报错:`view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value.如果将非日期时间值传递给具有日期时间单位

的轴,通常会发生这种情况

部分数据截图如下:Frame Frame1

非常感谢您的帮助!谢谢!

如果您将 'Start Time and Date' 列的格式保留为默认 pandas 日期时间格式不变,而是更新 x 轴刻度标签的格式,您的代码应该可以正常工作。

import pandas as pd

frame = pd.DataFrame({'Start Time and Date': ['2013-07-01 00:00:00', '2013-07-01 00:00:02', '2013-07-01 00:01:04',
                                              '2013-07-01 00:01:06', '2013-07-01 00:01:10', '2013-08-01 00:00:00',
                                              '2013-08-01 00:00:02', '2013-09-01 00:01:04', '2013-09-01 00:01:06',
                                              '2013-10-01 00:01:10', '2013-10-01 00:02:10', '2013-11-01 00:03:10',
                                              '2013-12-01 00:03:10', '2013-12-02 00:04:10', '2013-12-03 00:05:10'],
                      'index': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]})

# Number of records per month
line_chart = frame.copy()
line_chart.index = pd.DatetimeIndex(line_chart['Start Time and Date'])
line_chart = pd.DataFrame(line_chart.resample('M')['index'].count())
line_chart.reset_index(inplace=True)

# Plotly
import plotly.express as px

fig = px.line(line_chart, x='Start Time and Date', y='index')
fig.update_layout(xaxis=dict(tickformat='%m-%Y'))
fig.show()

# Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = line_chart['Start Time and Date']
y = line_chart['index']

fig, ax = plt.subplots(figsize=(10, 6))
plt.plot(x, y)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%Y'))
plt.show()