You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将日期转为年月Period类型后绘制折线图遇报错求助

Fixing Plotly & Matplotlib Errors for Monthly Record Count Line Charts

Hey Laura, let’s work through these plotting issues step by step. The core problems here are twofold: your date data is in Period format (which both libraries struggle with directly), and you haven’t actually calculated the monthly record counts yet (your current Y-axis uses the original row index instead of aggregated counts). Let’s fix both:

Step 1: Properly Calculate Monthly Record Counts

First, let’s aggregate your data to get the number of records per month—this is the Y-axis value you need. Instead of just copying columns, group by the monthly period and count entries:

# Convert your datetime column to monthly periods
frame['month'] = frame['Start Time and Date'].dt.to_period('M')

# Calculate monthly record counts (group by month, count entries)
monthly_counts = frame.groupby('month').size().reset_index(name='record_count')

This gives you a clean dataframe with two columns: month (the monthly period) and record_count (the number of entries for that month).


Fixing Plotly’s "Object of type Period is not JSON serializable" Error

Plotly can’t serialize Period objects directly. You have two easy fixes:

Option 1: Convert Period to String

Convert the month column to a string—Plotly handles this seamlessly:

import plotly.express as px

# Convert Period to string format
monthly_counts['month_str'] = monthly_counts['month'].astype(str)

# Create the line chart
fig = px.line(
    monthly_counts,
    x='month_str',
    y='record_count',
    title='Monthly Record Counts',
    labels={'month_str': 'Month', 'record_count': 'Number of Records'}
)
fig.show()

Option 2: Convert Period to Datetime

If you want to keep date-specific formatting options (like automatic tick spacing), convert the Period to a datetime (using the first day of each month):

monthly_counts['month_datetime'] = monthly_counts['month'].dt.to_timestamp()

fig = px.line(
    monthly_counts,
    x='month_datetime',
    y='record_count',
    title='Monthly Record Counts'
)
fig.update_xaxes(title='Month')
fig.update_yaxes(title='Number of Records')
fig.show()

Fixing Matplotlib’s "Invalid Date Value" Error

Matplotlib expects datetime64 objects instead of Periods. Convert the Period column to a datetime, then plot:

import matplotlib.pyplot as plt

# Convert Period to datetime (first day of the month)
monthly_counts['month_datetime'] = monthly_counts['month'].dt.to_timestamp()

# Create and style the line chart
plt.figure(figsize=(10, 6))
plt.plot(monthly_counts['month_datetime'], monthly_counts['record_count'], marker='o', color='#1f77b4')
plt.gcf().autofmt_xdate()  # Rotate x-axis labels for readability
plt.title('Monthly Record Counts', fontsize=14)
plt.xlabel('Month', fontsize=12)
plt.ylabel('Number of Records', fontsize=12)
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()

Key Notes

  • Always aggregate first: Your original code used the row index as the Y-value, which doesn’t represent monthly counts—grouping with groupby().size() fixes this.
  • Avoid raw Periods for plotting: Both libraries work better with strings or datetime objects instead of Pandas Period types.

内容的提问来源于stack exchange,提问作者Laura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:17:52