5

введите сюда описание изображения

Есть график сверху. Хочу попробовать его воспроизвести из этих данных.

Делаю это так:

def month2season(month):
    if 1 <= month <= 2 or month == 12:
        return 'winter'
    elif 3 <= month <= 5:
        return 'spring'
    elif 6 <= month <= 8:
        return 'summer'
    elif 9 <= month <= 11:
        return 'autumn'

df = pd.read_csv('https://raw.githubusercontent.com/ternikov/hse/gh-pages/hw5/temp_data.csv')
df_grouped = df.groupby(['year', 'month'], as_index=False).mean()
df_grouped['season'] = df_grouped['month'].apply(month2season)

fig, ax = plt.subplots(2, 2, figsize=(15, 10))
for season_data, axes in zip(df_grouped['season'].unique(), ax.reshape(-1)):
    season_data = df_grouped[df_grouped['season'] == season_data]
    sns.lineplot('year', 'temp', data=season_data, ax=axes)
plt.show()

Но проблема в том, что lineplot соединяет участок с пропущенными значениями таким образом:

введите сюда описание изображения

Каким образом можно исправить?

1 ответ 1

6

После недолгого экспериментирования оказалось, что Seaborn отбрасывает значение бесконечности (np.inf), а для значений NaN (np.nan) - соединяет ближайшие значимые (not NaN):

def month2season(m):
    seasons = ["Winter", "Spring", "Summer", "Autumn"]
    return np.take(seasons, (m % 12) // 3)

df = pd.read_csv("https://raw.githubusercontent.com/ternikov/hse/gh-pages/hw5/temp_data.csv")
int_cols = ["year", "month"]
df[int_cols] = df[int_cols].astype(int)

res = pd.DataFrame(list(product(range(1952, 2017), range(1, 13))), columns=int_cols)
res = res.merge(df, how="left")
res["season"] = res["month"].map(month2season)

fig, axes = plt.subplots(2, 2, figsize=(15, 10))

for season, ax in zip(res['season'].unique(), axes.ravel()):
    sns.lineplot('year', 'temp', data=res[res['season'] == season].fillna(np.inf), ax=ax)

введите сюда описание изображения

1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.