简体   繁体   中英

Pandas - seaborn lineplot hue unexpected legend

I have a data frame of client names, dates and transactions. I'm not sure how far back my error goes, so here is all the pre-processing I do:

data = pd.read_excel('Test.xls')
## convert to datetime object 
data['Date Order'] = pd.to_datetime(data['Date Order'], format = '%d.%m.%Y')
## add columns for month and year of each row for easier analysis later
data['month'] = data['Date Order'].dt.month
data['year'] = data['Date Order'].dt.year  

So the data frame becomes something like:

Date Order           NameCustomers         SumOrder          month         year
2019-01-02 00:00:00   Customer 1             290              1            2019  
2019-02-02 00:00:00   Customer 1             50               2            2019  
----- 
2020-06-28 00:00:00   Customer 2             900              6            2020
------ 

..etc. You get the idea. Next I group by both month and year and calculate the mean.

groupedMonthYearMean = data.groupby(['month', 'year'])['SumOrder'].mean().reset_index()

Output:

month    year    SumOrder 
1        2019    233.08
1        2020    303.40
2        2019    255.34   
2        2020    842.24
--------------------------

I use the resulting dataframe to make a lineplot, which tracks the SumOrder for each month, and displays it for each year.

linechart = sns.lineplot(x = 'month', 
                         y = 'SumOrder', 
                         hue = 'year',
                         data = groupedMonthYearMean).set_title('Mean Sum Order by month')
plt.show()

I have attached a screenshot of the resulting plot - overall it seems to show what I expected to create. In my entire data, the 'year' column has only two values: 2019 and 2020. For some reason, whatever I do, they show up as 0, -1 and -2. Any ideas what is going on?

意想不到的色调传奇

You want to change the dtype of the year column from int to category

df['year'] = df['year'].astype('category')

This is due to how hue treats ints.

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