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

如何将DataFrame每行数据绘制成折线图并解决x y维度不匹配报错

报错原因

plt.plot()要求输入的x序列和y序列长度必须完全相等,你当前每条折线的x只有2个时间点(频道创建日期、当前日期),如果直接用range(0, 订阅数)生成y,会得到长度和订阅数数值相等的超长序列,和x的长度2不匹配,所以触发维度不一致的报错。
你临时使用的y1 = range(len(x1))虽然能正常运行,但生成的y值只有[0,1],和实际的订阅数完全不匹配,所以生成的图表不符合预期。

修复后可运行代码
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

channel_data = pd.DataFrame({
    'Creation date': ['2014-01-02', '2013-09-11', '2007-08-19'], 
    'Subscriber count': [6060000, 4110000, 4440000]
})

now = dt.date.today() # 直接获取当前日期,不需要手动转字符串再解析

# 生成各频道的x、y序列,每个序列都只有2个元素,长度匹配
x1 = [dt.datetime.strptime(channel_data["Creation date"][0],'%Y-%m-%d').date(), now]
x2 = [dt.datetime.strptime(channel_data["Creation date"][1],'%Y-%m-%d').date(), now]
x3 = [dt.datetime.strptime(channel_data["Creation date"][2],'%Y-%m-%d').date(), now]

# y序列为两个值:创建日订阅数0、当前日期订阅数
y1 = [0, channel_data["Subscriber count"][0]]
y2 = [0, channel_data["Subscriber count"][1]]
y3 = [0, channel_data["Subscriber count"][2]]

plt.figure(figsize=(10, 5))
plt.title("Channel growth over time", fontdict={"fontweight": "bold"}) # 原标题的[USD]和y轴订阅数不符,已移除可按需调整

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator()) # 补充设置年份刻度间隔,显示更清晰

plt.plot(x1, y1, "b.-", label="Carwow")
plt.plot(x2, y2, "r.-", label="Doug Demuro")
plt.plot(x3, y3, "g.-", label="Scotty Kilmer")

plt.xlabel("Date", fontdict={"fontsize": 13})
plt.ylabel("Subscribers", fontdict={"fontsize": 12})

plt.legend()
plt.grid(alpha=0.3) # 可选添加网格,可读性更好
plt.show()
优化方向
  • 避免硬编码单条折线的逻辑:如果后续频道数量增加,可以直接遍历DataFrame行生成折线,无需重复写重复代码,示例如下:
colors = ['b', 'r', 'g']
labels = ["Carwow", "Doug Demuro", "Scotty Kilmer"]
for idx, row in channel_data.iterrows():
    x = [dt.datetime.strptime(row["Creation date"],'%Y-%m-%d').date(), dt.date.today()]
    y = [0, row["Subscriber count"]]
    plt.plot(x, y, f"{colors[idx]}.-", label=labels[idx])
  • 如果后续获取到真实的历史订阅数时序数据,直接把x替换为真实的日期序列、y替换为对应日期的订阅数序列,只要保证两者长度一致即可正常绘图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 19:54:03