首页 > 解决方案 > Seaborn Lineplot 显示索引错误,pandas 绘图正常

问题描述

我在使用 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

谢谢你。

标签: pythonpython-3.xseaborn

解决方案


你得到的原因IndexError是因为你的ax对象是一个二维数组,你在第一个(长度=1)维度上建立索引:

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

如果您想在同一个图上绘制多条线,您可以ax通过将其传递给seaborn这样的方式让它们共享相同:

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

在此处输入图像描述


推荐阅读