[英]Generating a Line Graph using Seaborn or Matplotlib with: Year as hue, Month as X-Axis and Float Column as Y-Axis
The problem is I'm trying to generate a line graph using seaborn.lineplot() function, but I can't seem to find a way to generate a line graph like the one below:问题是我正在尝试使用 seaborn.lineplot() function 生成折线图,但我似乎找不到像下面这样生成折线图的方法:
https://i.stack.imgur.com/zUKog.png https://i.stack.imgur.com/zUKog.png
My dataset has the following columns: Year, Month, Day, Units, Price per Unit, Sales.我的数据集有以下列:年、月、日、单位、单位价格、销售额。 I've used the groupby function from pandas to sum the sales for each year in each month.
我使用来自 pandas 的 groupby function 来总结每个月每年的销售额。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
years_list = [date.strftime('%Y/%#-m/%#-d') for date in pd.date_range('01/01/2000', '31/12/2019')]
data = {
'year': [int(date.split('/')[0]) for date in years_list],
'month': [int(date.split('/')[1]) for date in years_list],
'day': [int(date.split('/')[2]) for date in years_list],
'units': [np.random.randint(1,25) for turns in range(len(years_list))],
'price_per_unit': [np.random.uniform(10, 100) for turns in range(len(years_list))]
}
df = pd.DataFrame(data)
df['sales'] = df['price_per_unit'] * df['units']
each_month = df.groupby(['year', 'month'])['sales'].sum().reset_index()
Initially, I thought that using the code sns.lineplot(x='month', y='sales', hue='year', data=each_month)
would automatically generate my desired graph, but it generated a confusing graph instead.最初,我认为使用代码
sns.lineplot(x='month', y='sales', hue='year', data=each_month)
会自动生成我想要的图表,但它却生成了一个令人困惑的图表。
Anyone who has a solution for me?谁有我的解决方案? even if it isn't by using seaborn but matplotlib.
即使不是使用 seaborn 而是 matplotlib。
Yes, that line indeed creates what you want.是的,这条线确实创造了你想要的。 However, for numeric hue,
sns
automatically colors your line according to a continuous colormap.但是,对于数字色调,
sns
会根据连续的颜色图自动 colors 您的线。 To overcome this, you can convert your year
to string type:为了克服这个问题,您可以将
year
转换为字符串类型:
each_month['year'] = 'Y' + each_month['year'].astype(str)
plt.figure(figsize=(10,6))
sns.lineplot(x='month', y='sales', hue='year', data=each_month)
Output: Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.