python - 如何创建 Matplotlib 小提琴图
问题描述
我正在尝试让我的第一个 Matplotlib 小提琴情节继续进行,并且我正在使用此 SO 帖子中的确切代码,但出现 KeyError 错误。我不知道那是什么意思。有任何想法吗?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = np.random.poisson(lam =3, size=100)
y = np.random.choice(["S{}".format(i+1) for i in range(6)], size=len(x))
df = pd.DataFrame({"Scenario":y, "LMP":x})
fig, axes = plt.subplots()
axes.violinplot(dataset = [df[df.Scenario == 'S1']["LMP"],
df[df.Scenario == 'S2']["LMP"],
df[df.Scenario == 'S3']["LMP"],
df[df.Scenario == 'S4']["LMP"],
df[df.Scenario == 'S5']["LMP"],
df[df.Scenario == 'S6']["LMP"] ] )
错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-6-cd0789171d00> in <module>
15 df[df.Scenario == 'S4']["LMP"],
16 df[df.Scenario == 'S5']["LMP"],
---> 17 df[df.Scenario == 'S6']["LMP"] ] )
18
19 # axes.set_title('Day Ahead Market')
c:\Anaconda\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
1808 "the Matplotlib list!)" % (label_namer, func.__name__),
1809 RuntimeWarning, stacklevel=2)
-> 1810 return func(ax, *args, **kwargs)
1811
1812 inner.__doc__ = _add_data_doc(inner.__doc__,
c:\Anaconda\lib\site-packages\matplotlib\axes\_axes.py in violinplot(self, dataset, positions, vert, widths, showmeans, showextrema, showmedians, points, bw_method)
7915 return kde.evaluate(coords)
7916
-> 7917 vpstats = cbook.violin_stats(dataset, _kde_method, points=points)
7918 return self.violin(vpstats, positions=positions, vert=vert,
7919 widths=widths, showmeans=showmeans,
c:\Anaconda\lib\site-packages\matplotlib\cbook\__init__.py in violin_stats(X, method, points)
1460 # Evaluate the kernel density estimate
1461 coords = np.linspace(min_val, max_val, points)
-> 1462 stats['vals'] = method(x, coords)
1463 stats['coords'] = coords
1464
c:\Anaconda\lib\site-packages\matplotlib\axes\_axes.py in _kde_method(X, coords)
7910 def _kde_method(X, coords):
7911 # fallback gracefully if the vector contains only one value
-> 7912 if np.all(X[0] == X):
7913 return (X[0] == coords).astype(float)
7914 kde = mlab.GaussianKDE(X, bw_method)
c:\Anaconda\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
765 key = com._apply_if_callable(key, self)
766 try:
--> 767 result = self.index.get_value(self, key)
768
769 if not is_scalar(result):
c:\Anaconda\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
3116 try:
3117 return self._engine.get_value(s, k,
-> 3118 tz=getattr(series.dtype, 'tz', None))
3119 except KeyError as e1:
3120 if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 0
解决方案
KeyError
每当在容器中查找项目失败时都会引发A。这些查找中使用的值是keys,错误意味着0
不是数据帧的有效键。
DataFrame
对象不是传统的 NumPy 数组。它们包含一个索引,可根据或多或少的任意信息(包括数字数据、日期、字符串等)快速查找数据。这与标准 s 形成对比,标准ndarray
s 仅允许线性索引(即位置)作为有效键。因此,当您执行类似的操作时df[0]
,这是尝试0
在框架的索引中查找值,而不是检索数组中的第一项。
但是,如果您这样做df[df.Scenario == 'S1']['LMP'].index
,您应该会看到:
Int64Index([8, 20, 25, 27, 28, 35, 52, 57, 62, 68, 72, 74, 77, 80, 81, 83, 97], dtype='int64')
请注意,0
无处可寻,因此KeyError
. matplotlib
旨在使用 NumPyndarray
对象,而不是 PandasDataFrame
对象。它对这种花哨的索引一无所知,因此这些类型的错误很常见。
你有几个选择来解决这个问题。首先,将您想要绘制的数据转换为数组。df[df.Scenario == 'S1']['LMP'].values
对于每个这样的数组,您可以使用 , 来执行此操作。
另一种是使用类似 的包seaborn
,它明确设计用于处理 Pandas 框架。我强烈推荐 Seaborn,它是一个非常漂亮且设计精良的包装。例如,它有自己的 s 版本violinplot
,它支持DataFrame
s 和一大堆选项。
推荐阅读
- firebase - 从 Firebase 控制台手动删除文档而不删除子集合时,我应该怎么做才能触发 onDelete firebase 功能?
- python - 在python中将日期转换为列表
- docker - 一个运行 Apache 的容器内的多个站点:来自外部的虚拟主机?
- c# - 如何返回 DispatcherOperation
从模拟对象 - sql - SQL Server CTE 层次结构数据类型转换
- angular - 如何在 Angular 中翻译库而不在应用程序中初始化翻译服务?
- c++ - 无效密码导致无限显示循环
- batch-file - 如何从批处理文件运行多个命令?
- javascript - JS - 我可以导入具有多个文件的同名导出吗?
- c++ - 是否可以使用 std::pair 作为 std::set 的键而每个元素没有任何重复?