如何使用带有 x 轴的 seaborn 实现线图 "Date"



我试图实施Seaborn Lineplot

  1. 数据框架将日期值列表作为索引,试图将其作为X轴。dataframe.info将"日期"字段显示为对象
  2. 我需要以x轴
  3. 日期的4种类型的列值的线路图
  4. 当我尝试执行以下代码时,将错误消息显示为
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

如果我误解了这个问题,请提前提前。

我看到的方式是,您需要使用日期作为X轴将给定类别的整数值绘制为y轴。

我创建了此示例数据框:

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')

最新更新