【发布时间】:2019-03-27 20:50:07
【问题描述】:
我有一个跨越 4 年的数据集,我想将其绘制在图表上,每一年都作为一个单独的系列。我的数据是从 2015 年 3 月到 2018 年 8 月的每日详细信息,我想按月汇总和显示。
plt.clf() # clear figures
plt.figure(figsize=(16,8))
x = np.arange(0, 12, 1)
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
total_sales_2015 = train.loc[train['Year'] == '2015'].groupby('Month')['SalesValue'].sum()/1000.0 # format into thousands
total_sales_2016 = train.loc[train['Year'] == '2016'].groupby('Month')['SalesValue'].sum()/1000.0 # format into thousands
total_sales_2017 = train.loc[train['Year'] == '2017'].groupby('Month')['SalesValue'].sum()/1000.0 # format into thousands
total_sales_2018 = train.loc[train['Year'] == '2018'].groupby('Month')['SalesValue'].sum()/1000.0 # format into thousands
plt.plot(x, total_sales_2015, label="2015") <-- doesn't work, as only 10 data points
plt.plot(x, total_sales_2016, label="2016") <-- does work
plt.plot(x, total_sales_2017, label="2017") <-- does work
plt.plot(x, total_sales_2018, label="2018") <-- doesn't work, as only 8 data points
如何在图表上显示部分年份?当我运行上面的代码时,它会产生以下错误:“ValueError: x and y must have same first dimension”
【问题讨论】:
-
有几件事:没有样本数据很难给出准确的反馈。其次,如果您按月分组,那么只有 10 个数据点并不是那么荒谬,因为您可能会错过两个月。
-
@Yuca:我的数据只能追溯到 2015 年 3 月,这很好,我只想将那一年的 10 个月值与随后年份的值进行比较。
-
那么当你应该得到 10 个数据点时,你为什么说它不起作用(“只有 10 个数据点”)?
-
因为 matplotlib 期望该系列包含与 x 轴相同数量的值,12。当我运行代码时,我得到“ValueError:x 和 y 必须具有相同的第一维”跨度>
-
刚刚在另一个 SO 问题上找到了答案。
标签: python pandas matplotlib plot