繁体   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