def cal_anomaly_M(df, df_ref):
    """
    Calculates monthly averaged temperature anomaly (departure) from the reference period.
    Parameters:
        - df: DataFrame from which anomaly is calculated
        - df_ref: DataFrame of the reference period
    Returns:
        - df_M: monthly averaged anomaly
        - df_ref_M: monthly averaged reference temperatures
    """
    # reference frame:
    df_ref_tmp = df_ref.resample('MS').mean()
    df_ref_tmp['M_num'] = df_ref_tmp.index.month
    df_ref_M = df_ref_tmp.groupby('M_num').mean()

    # plotting frame:
    df_M = df.resample('MS').mean() # this will fill incomplete months into complete ones and place the mean into the first day of the month
    df_M['M_num'] = df_M.index.month

    # calculate anomaly:
    for num in set(df_M['M_num']):
        df_M['value'][df_M['M_num'] == num] -= df_ref_M['value'][num]
    
    return df_M, df_ref_M