簡體   English   中英

使用 Seaborn 或 Matplotlib 生成折線圖,其中:年為色調,月為 X 軸,浮點列為 Y 軸

[英]Generating a Line Graph using Seaborn or Matplotlib with: Year as hue, Month as X-Axis and Float Column as Y-Axis

問題是我正在嘗試使用 seaborn.lineplot() function 生成折線圖,但我似乎找不到像下面這樣生成折線圖的方法:

https://i.stack.imgur.com/zUKog.png

我的數據集有以下列:年、月、日、單位、單位價格、銷售額。 我使用來自 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()

最初,我認為使用代碼sns.lineplot(x='month', y='sales', hue='year', data=each_month)會自動生成我想要的圖表,但它卻生成了一個令人困惑的圖表。

誰有我的解決方案? 即使不是使用 seaborn 而是 matplotlib。

是的,這條線確實創造了你想要的。 但是,對於數字色調, sns會根據連續的顏色圖自動 colors 您的線。 為了克服這個問題,您可以將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:

在此處輸入圖像描述

month設置為索引,然后按year分組,然后只是 plot sales

each_month.set_index('month').groupby('year').sales.plot(legend=True, figsize=(10, 6))

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM