簡體   English   中英

plot 在 12 個月軸上同比

[英]plot year over year on 12 month axis

我想要 plot 從 12 月到 1 月的一個 12 個月軸上的 6 年 12 個月期間數據。

import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

df = pd.Series(np.random.randn(72), index=pd.date_range('1/1/2000', periods=72, freq='M'))

# display(df.head())
2000-01-31    0.713724
2000-02-29    0.416233
2000-03-31   -0.147765
2000-04-30    0.141021
2000-05-31    0.966261
Freq: M, dtype: float64

grouped = df.groupby(df.index.map(lambda x: x.year))

grouped.plot()

在此處輸入圖像描述

我每年都在休息。 然而,我想做的是讓年份相互疊加。 有什么簡單干凈的方法嗎?

可能有一個比這更好的方法:

In [44]: vals = df.groupby(lambda x: (x.year, x.month)).sum()

In [45]: vals
Out[45]: 
(2000, 1)    -0.235044
(2000, 2)    -1.196815
(2000, 3)    -0.370850
(2000, 4)     0.719915
(2000, 5)    -1.228286
(2000, 6)    -0.192108
(2000, 7)    -0.337032
(2000, 8)    -0.174219
(2000, 9)     0.605742
(2000, 10)    1.061558
(2000, 11)   -0.683674
(2000, 12)   -0.813779
(2001, 1)     2.103178
(2001, 2)    -1.099845
(2001, 3)     0.366811
...
(2004, 10)   -0.905740
(2004, 11)   -0.143628
(2004, 12)    2.166758
(2005, 1)     0.944993
(2005, 2)    -0.741785
(2005, 3)     1.531754
(2005, 4)    -1.106024
(2005, 5)    -1.925078
(2005, 6)     0.400930
(2005, 7)     0.321962
(2005, 8)    -0.851656
(2005, 9)     0.371305
(2005, 10)   -0.868836
(2005, 11)   -0.932977
(2005, 12)   -0.530207
Length: 72, dtype: float64

現在改變指數valsMultiIndex

In [46]: vals.index = pd.MultiIndex.from_tuples(vals.index)

In [47]: vals.head()
Out[47]: 
2000  1   -0.235044
      2   -1.196815
      3   -0.370850
      4    0.719915
      5   -1.228286
dtype: float64

然后拆散並繪圖:

In [48]: vals.unstack(0).plot()
Out[48]: <matplotlib.axes.AxesSubplot at 0x1171a2dd0>

在此輸入圖像描述

  1. 如果數據是pandas.DataFrame而不是pandas.Series ,我認為它更清晰,更容易轉換。
    • OP 中的示例數據是pandas.Series ,但如果我們從pandas.DataFrame開始,對於希望解決此問題的人來說它會更典型,所以我們將首先使用.to_frame()
  2. 提取datetime時間索引的monthyear部分。
    • 該索引已經是datetime dtype 如果您的數據不是,請使用pd.to_datetime()轉換日期索引/列
    • 如果數據是列,而不是索引,則使用.dt訪問器獲取monthyear (例如df[col].dt.yeardf.index.year
  3. 使用pandas.pivot_table將 dataframe 從長格式轉換為寬格式,並匯總數據(例如'sum''mean'等)
    • 這將 dataframe 變成了正確的形狀,很容易變成 plot,無需拆分和進一步操作。
    • 索引將始終是 x 軸,並且將繪制列。
    • 如果給定'month'沒有重復數據,則不需要聚合,則使用pandas.DataFrame.pivot
  4. Plot 旋轉 dataframe 與pandas.DataFrame.plot
  • python 3.11 pandas 1.5.2 matplotlib 3.6.2中測試
import pandas as pd

# for this OP convert the Series to a DataFrame
df = df.to_frame()

# extract month and year from the index and create columns
df['month'] = df.index.month
df['year'] = df.index.year

# display(df.head(3))
                   0  month  year
2000-01-31  0.167921      1  2000
2000-02-29  0.523505      2  2000
2000-03-31  0.817376      3  2000

# transform the dataframe to a wide format
dfp = pd.pivot_table(data=df, index='month', columns='year', values=0, aggfunc='sum')

# display(dfp.head(3))
year       2000      2001      2002      2003      2004      2005
month                                                            
1      0.167921  0.637999 -0.174122  0.620622 -0.854315 -1.523579
2      0.523505 -0.344658 -0.280819  0.845543  0.782439 -0.593732
3      0.817376 -0.004282 -0.907424  0.352655  1.258275 -0.624112

# plot; us xticks=dfp.index so every month number is displayed
ax = dfp.plot(ylabel='Aggregated Sum', figsize=(6, 4), xticks=dfp.index)
# reposition the legend
ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')

在此處輸入圖像描述

  • 要在軸上獲取月份名稱,請使用以下內容創建'month'列:
    • df['month'] = df.index.strftime('%b') ,得到月份縮寫
from calendar import month_abbr  # this is a sorted list of month name abbreviations

# for this OP convert the Series to a DataFrame
df = df.to_frame()

# extract the month abbreviation
df['month'] = df.index.strftime('%b')
df['year'] = df.index.year

# transform
dfp = pd.pivot_table(data=df, index='month', columns='year', values=0, aggfunc='sum')

# the dfp index so the x-axis will be in order
dfp = dfp.loc[month_abbr[1:]]

# display(dfp.head(3))
year       2000      2001      2002      2003      2004      2005
month                                                            
Jan    0.167921  0.637999 -0.174122  0.620622 -0.854315 -1.523579
Feb    0.523505 -0.344658 -0.280819  0.845543  0.782439 -0.593732
Mar    0.817376 -0.004282 -0.907424  0.352655  1.258275 -0.624112

# plot; using xticks=range(12) will result in all the xticks being labeled with a month, otherwise not all ticks will be displayed
ax = dfp.plot(ylabel='Aggregated Sum', figsize=(6, 4), xticks=range(12))
ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')

在此處輸入圖像描述

  • 此數據是離散數據,因為它是聚合的,所以它確實應該繪制為條形 plot。
ax = dfp.plot(kind='bar', ylabel='Aggregated Sum', figsize=(12, 4), rot=0)
ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM