python - 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
但是,以下行完美地显示了绘图,没有任何错误:
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)维度上建立索引:
挤压 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()
推荐阅读
- python - Django 3.0.8 URL/模板/路由问题“没有反向匹配”
- database - 连接表 vs 链接表 vs 连接表 vs 桥接表
- ios - 如何在 Swift 中显示本地通知的动态正文文本
- hadoop - 容器是如何创建的,它是如何工作的?
- azure - 发布到 Azure 时序见解时,环境不支持 API“元数据”
- ruby-on-rails - 如何让浏览器等待 Capybara & Kimurai?
- python - 仅在第一次运行中获取 LinAlgError SVD 未在 sm.OLS.fit() 中收敛 err
- flask - 下载并最终执行 Flask 以使其工作或连接到网络
- python - Python,使用追加列表更改子内容时父更改
- java - 菜单项的 Android 应用程序语言没有改变,尽管它改变了片段和活动等其他所有内容