Seaborn的Lineplot没有绘制正确的多线图

时间:2020-08-29 10:10:57

标签: python seaborn python-datetime line-plot

我正在尝试制作多线图,其中一条线显示2019年1月至7月的每日计数信息,另一条线显示2020年的情况。 在绘制图形之前,我还使用pd.concat“垂直”组合了2019年数据框和2020年数据框,使组合的框适合作为seaborn线图函数的输入数据集。但是,结果有些混乱:

enter image description here

plt.figure(figsize=(18,6))

ax5 = sns.lineplot(x='OBSERVATION_DATE_ONLY', y='OBSERVATION_COUNT', hue='OBSERVATION_YEAR', data=Bird_Concat1920['rinphe'])

#Reset x and y axis labels
ax5.set_xlabel('Observation Date')
ax5.set_ylabel('Observation Count')
ax5.xaxis.labelpad = 15
ax5.yaxis.labelpad = 15

这是级联数据帧外观的快照:

enter image description here

1 个答案:

答案 0 :(得分:0)

有两点:首先,2020年是a年,因此我们删除2月29日,其次,x轴上的数据设置为相同的数字,而未到达数据设置为NA。

>
import pandas as pd
import numpy as np

date_2019 = pd.date_range('2019-01-01', '2019-12-31', freq='1D')
date_2020 = pd.date_range('2020-01-01', '2020-12-31', freq='1D')
val_2019 = np.random.randint(100, 300, (365,))
val_2020 = np.random.randint(100, 300, (241,))
val_2020 = np.insert(val_2020.astype(float),len(val_2020),[np.NaN]*125)
df_2019 = pd.DataFrame({'Date':date_2019, 'OBSERVATION_COUNT': val_2019})
df_2020 = pd.DataFrame({'Date':date_2020, 'OBSERVATION_COUNT': val_2020})
df_2020 = df_2020[df_2020['Date'] != '2020-02-29']
Bird_Concat1920 = pd.concat([df_2019, df_2020], axis=0)
Bird_Concat1920['Date'] = pd.to_datetime(Bird_Concat1920['Date'])
Bird_Concat1920['OBSERVATION_YEAR'] = Bird_Concat1920['Date'].apply(lambda x:'Year_'+ str(x.year))
Bird_Concat1920['OBSERVATION_DATE_ONLY'] = Bird_Concat1920['Date'].apply(lambda x: x.strftime('%m-%d'))

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig = plt.figure(figsize=(18,6))

ax5 = sns.lineplot(x='OBSERVATION_DATE_ONLY', y='OBSERVATION_COUNT', hue='OBSERVATION_YEAR', data=Bird_Concat1920)

#Reset x and y axis labels
ax5.set_xlabel('Observation Date')
ax5.set_ylabel('Observation Count')
ax5.xaxis.labelpad = 15
ax5.yaxis.labelpad = 15

months = mdates.MonthLocator(interval=1)
months_fmt = mdates.DateFormatter('%b')
ax5.xaxis.set_major_locator(months)
ax5.xaxis.set_major_formatter(months_fmt)

enter image description here