简体   繁体   中英

Wrong monthly lineplot using seaborn, pandas and datetime

I am trying to create the following diagram, but with the written months as xticks instead of the integer:

几乎正确

My code currently looks like this:

plt.figure(figsize=(10,5))
sns.lineplot(x="Month",y="DHN",data = df.head(1100),color="BLACK")
sns.lineplot(x="Month",y="Heat Loss",data = df.head(1100),color ="RED")

Which results in:

在此处输入图片说明

Obviously, multiple things are wrong with this diagram. The Diagram x axis should start with January, the values inside the dataframe are getting stacked for the months (?) and the scale for df.head(1100) should not inclued months like december or september.

The first lines of the Dataframe look like this:

在此处输入图片说明

with Date as datetime.

What am I missing that it's not working out the way I want it to?

Convert Month column to ordered categorical s for correct ordering values in axis x in ploting:

cats = ['Jan', 'Feb', 'Mar', 'Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
df['Month'] = pd.Categorical(df['Month'], ordered=True, categories=cats)

plt.figure(figsize=(10,5))
sns.lineplot(x="Month",y="DHN",data = df.head(1100),color="BLACK")
sns.lineplot(x="Month",y="Heat Loss",data = df.head(1100),color ="RED")

Sample :

np.random.seed(123)

def random_dates(start, end, n=100):

    start_u = start.value//10**9
    end_u = end.value//10**9

    return pd.to_datetime(np.random.randint(start_u, end_u, n), unit='s')

start = pd.to_datetime('2015-01-01')
end = pd.to_datetime('2017-01-20')
df = pd.DataFrame({'Date':random_dates(start, end),
                   'DHN':np.random.randint(500, size=100),
                   'Heat Loss':np.random.randint(50, size=100)})
df['Month'] = df['Date'].dt.strftime('%b')
df = df.sort_values('Date')
print (df.head())

                  Date  DHN  Heat Loss Month
55 2015-01-07 20:29:22  296         23   Jan
29 2015-01-08 13:49:04  486         18   Jan
36 2015-01-15 23:32:55  294          9   Jan
59 2015-01-19 10:33:39  256          5   Jan
72 2015-01-19 19:48:43  254          3   Jan

cats = ['Jan', 'Feb', 'Mar', 'Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
df['Month'] = pd.Categorical(df['Month'], ordered=True, categories=cats)

plt.figure(figsize=(10,5))
sns.lineplot(x="Month",y="DHN",data = df.head(1100),color="BLACK")
sns.lineplot(x="Month",y="Heat Loss",data = df.head(1100),color ="RED")

图形

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM