繁体   English   中英

Seaborn Lineplot 显示索引错误,pandas 绘图正常

[英]Seaborn Lineplot displays Index error, pandas plot fine

我在使用 Seaborn 线图显示数据时遇到了一个有趣的问题。

我在一段时间内销售了 5 件商品。 我想看看每个产品推出后的销售情况。

这是我的代码:

items  = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']

fig, ax = plt.subplots(squeeze=False)
ax[0] = sns.lineplot(x=item_sales.index, y='Item 1', data=item_sales, alpha=0.2) 
ax[1] = sns.lineplot(x=item_sales.index, y='Item 2', data=item_sales, alpha=0.2) 
ax[2] = sns.lineplot(x=item_sales.index, y='Item 3', data=item_sales, alpha=0.2) 
ax[3] = sns.lineplot(x=item_sales.index, y='Item 4', data=item_sales, alpha=0.4)
ax[4] = sns.lineplot(x=item_sales.index, y='Item 5', data=item_sales, alpha=0.2)
ax.set_ylabel('')  
ax.set_yticks([])
plt.title('Timeline of item sales')
plt.show()

此代码错误显示以下行,但绘制了 2 行:

ax[1] = sns.lineplot(x=item_sales.index, y='Item 2', data=item_sales, alpha=0.2) 

IndexError: index 1 is out of bounds for axis 0 with size 1

Seaborn 线图

但是,以下行完美地显示了绘图,没有任何错误:

item_sales.plot()

在此处输入图片说明

出现上述错误的原因可能是什么 - 数据非常干净并且没有缺失值:

item_sales.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 36 entries, 0 to 35
Data columns (total 6 columns):
 #   Column        Non-Null Count  Dtype 
---  ------        --------------  ----- 
 0   Date Created  36 non-null     object
 1   Item 1        36 non-null     int64 
 2   Item 2        36 non-null     int64 
 3   Item 3        36 non-null     int64 
 4   Item 4        36 non-null     int64 
 5   Item 5        36 non-null     int64 
dtypes: int64(5), object(1)
memory usage: 1.8+ KB

谢谢你。

您收到IndexError的原因是因为您的ax对象是一个二维数组,并且您正在索引第一个(长度 = 1)维度:

挤压布尔值,默认值:True
如果为 False,则根本不进行压缩:返回的 Axes 对象始终是包含 Axes 实例的二维数组,即使它最终是 1x1。

如果你想在同一个图上绘制多条线,你可以通过将它传递给seaborn让它们共享相同的axseaborn所示:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# prepare sample data
items  = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']
sales_data = dict(zip(items, np.random.randint(0, 25, (5, 30))))
item_sales = pd.DataFrame(sales_data)

fig, ax = plt.subplots(figsize=(8,4))

sns.set_palette("tab10", n_colors=5)
sns.lineplot(x=item_sales.index, y='Item 1', data=item_sales, alpha=0.3, ax=ax) 
sns.lineplot(x=item_sales.index, y='Item 2', data=item_sales, alpha=0.3, ax=ax) 
sns.lineplot(x=item_sales.index, y='Item 3', data=item_sales, alpha=0.3, ax=ax) 
sns.lineplot(x=item_sales.index, y='Item 4', data=item_sales, alpha=1, ax=ax)
sns.lineplot(x=item_sales.index, y='Item 5', data=item_sales, alpha=0.3, ax=ax)
ax.set_ylabel('')  
ax.set_yticks([])
plt.title('Timeline of item sales')
plt.show()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM