簡體   English   中英

如何使用 x 軸為“日期”的 seaborn 實現 Lineplot

[英]How to implement Lineplot using seaborn with x-axis as "Date"

我試圖實現seaborn lineplot

  1. 數據框將日期值列表作為索引,試圖使其成為 x 軸。 Dataframe.info 將“日期”字段顯示為對象
  2. 我需要以日期為 x 軸的 4 種類型的列值的線圖
  3. 當我嘗試執行以下代碼時,它顯示的錯誤消息為
ValueError: A wide-form input must have only numeric values.
<Figure size 720x360 with 0 Axes>
>>> sns.lineplot(data=file)
>>> plt.show()

Dataframe.info() message
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 59 entries, 0 to 58
Data columns (total 5 columns):
Date                                    59 non-null object
Avila Adobe                             59 non-null int64
Firehouse Museum                        59 non-null int64
Chinese American Museum                 59 non-null int64
America Tropical Interpretive Center    59 non-null int64
dtypes: int64(4), object(1)
memory usage: 2.4+ KB

如果我誤解了這個問題,請提前抱歉。

我的看法是,您需要將給定類別的整數值繪制為 y 軸,使用日期作為 x 軸。

我創建了這個示例數據框:

import pandas as pd

df = pd.DataFrame({
    'Avila Adobe': [11, 22, 33, 44, 55], 
    'Firehouse Museum': [13, 32, 23, 66, 54],
    'Chinese American Museum': [6, 15, 30, 40, 89],
    'America Tropical Interpretive Center': [40, 60, 80, 35, 17]
})

dates = pd.date_range('20190101', periods = 5)
df = df.set_index(dates)

所以表格看起來像這樣:

    Avila Adobe Firehouse Museum    Chinese American Museum America Tropical Interpretive Center
2019-01-01  11  13  6   40
2019-01-02  22  32  15  60
2019-01-03  33  23  30  80
2019-01-04  44  66  40  35
2019-01-05  55  54  89  17

我們在這里遇到的問題是數據以寬格式而不是長格式存儲。 因此,要為給定日期繪制這 4 列的值,您需要轉換數據框。

new_df = df.unstack().reset_index()
new_df.columns = ['Category', 'Date', 'Value']
new_df = new_df[['Date', 'Value', 'Category']]

現在長格式的表格如下所示:

    Date    Value   Category
0   2019-01-01  11  Avila Adobe
1   2019-01-02  22  Avila Adobe
2   2019-01-03  33  Avila Adobe
3   2019-01-04  44  Avila Adobe
4   2019-01-05  55  Avila Adobe
5   2019-01-01  13  Firehouse Museum
6   2019-01-02  32  Firehouse Museum
7   2019-01-03  23  Firehouse Museum
8   2019-01-04  66  Firehouse Museum
9   2019-01-05  54  Firehouse Museum
10  2019-01-01  6   Chinese American Museum
11  2019-01-02  15  Chinese American Museum
12  2019-01-03  30  Chinese American Museum
13  2019-01-04  40  Chinese American Museum
14  2019-01-05  89  Chinese American Museum
15  2019-01-01  40  America Tropical Interpretive Center
16  2019-01-02  60  America Tropical Interpretive Center
17  2019-01-03  80  America Tropical Interpretive Center
18  2019-01-04  35  America Tropical Interpretive Center
19  2019-01-05  17  America Tropical Interpretive Center

現在你可以用這樣的東西來繪制它:

import seaborn as sns
sns.lineplot(data=new_df, x='Date', y='Value', hue='Category')

暫無
暫無

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

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