Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建Matplotlib小提琴图_Python_Python 3.x_Matplotlib - Fatal编程技术网

Python 如何创建Matplotlib小提琴图

Python 如何创建Matplotlib小提琴图,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,我正在尝试让我的第一个Matplotlib小提琴图继续运行,我使用了这篇文章中的确切代码,但是得到了一个keyrerror错误。我不知道那是什么意思。有什么想法吗 错误: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython

我正在尝试让我的第一个Matplotlib小提琴图继续运行,我使用了这篇文章中的确切代码,但是得到了一个keyrerror错误。我不知道那是什么意思。有什么想法吗

错误:

---------------------------------------------------------------------------
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回溯(最近一次呼叫最后一次)
在里面
15 df[df.Scenario=='S4'][“LMP”],
16 df[df.Scenario=='S5'][“LMP”],
--->17 df[df.Scenario=='S6'][“LMP”]]
18
19轴。设置标题(“日前市场”)
c:\Anaconda\lib\site packages\matplotlib\\uuuu init\uuuuuu.py在内部(ax、数据、*args、**kwargs)
1808“Matplotlib列表!)”%(标签名称,函数名称),
1809运行时警告,堆栈级别=2)
->1810返回函数(ax,*args,**kwargs)
1811
1812内部.\uuuuu文档\uuuuu=\u添加数据\uu文档(内部.\uuuuu文档\uuuuuuuuuu),
violinplot中的c:\Anaconda\lib\site packages\matplotlib\axes\\u axes.py(自身、数据集、位置、垂直、宽度、显示平均值、显示极值、显示中间值、点、bw_方法)
7915返回kde.evaluate(coords)
7916
->7917 vpstats=cbook.visioner\u stats(数据集,kde\u方法,点=点)
7918返回自小提琴(vpstats,位置=位置,垂直=垂直,
7919宽度=宽度,显示方式=显示方式,
c:\Anaconda\lib\site packages\matplotlib\cbook\\uuuuuu init\uuuuuuuuuu.py在VIVISON\u统计中(X,方法,点)
1460#评估核密度估计值
1461坐标=np.linspace(最小值、最大值、点)
->1462统计数据['VAL']=方法(x,坐标)
1463统计数据['coords']=coords
1464
c:\Anaconda\lib\site packages\matplotlib\axes\\u axes.py in_kde_方法(X,coords)
7910定义方法(X,坐标):
7911#如果向量只包含一个值,则优雅地回退
->7912如果np.all(X[0]==X):
7913返回(X[0]==coords).astype(float)
7914 kde=mlab.GaussianKDE(X,bw_方法)
c:\Anaconda\lib\site packages\pandas\core\series.py in\uuuuu getitem\uuuuuuu(self,key)
765 key=com.\u如果可调用(key,self),则应用
766尝试:
-->767结果=self.index.get_值(self,key)
768
769如果不是标量(结果):
c:\Anaconda\lib\site packages\pandas\core\index\base.py in get\u value(self、series、key)
3116尝试:
3117返回自身引擎。获取值(s,k,
->3118 tz=getattr(series.dtype,“tz”,无))
3119除键错误为e1外:
3120如果len(self)>0且self.u输入['integer','boolean']:
pandas\\u libs\index.pyx在pandas.\u libs.index.IndexEngine.get\u value()中
pandas\\u libs\index.pyx在pandas.\u libs.index.IndexEngine.get\u value()中
熊猫\\u libs\index.pyx在熊猫中。\ u libs.index.IndexEngine.get_loc()
pandas\\u libs\hashtable\u class\u helper.pxi在pandas.\u libs.hashtable.Int64HashTable.get\u item()中
pandas\\u libs\hashtable\u class\u helper.pxi在pandas.\u libs.hashtable.Int64HashTable.get\u item()中
关键错误:0

当在容器中查找项目失败时,会引发
键错误
。这些查找中使用的值是键,错误表示
0
不是数据帧的有效键

DataFrame
对象不是传统的NumPy数组。它们包含一个索引,可以根据或多或少的任意信息快速查找数据,包括数字数据、日期、字符串等。这与标准的
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
设计用于NumPy
ndarray
对象,而不是Pandas
DataFrame
对象。它对这种奇特的索引一无所知,因此这些类型的错误很常见

您有几个选项可以解决此问题。首先,将要打印的数据转换为数组。您可以使用
df[df.Scenario=='S1']['LMP']]来完成此操作。对于每个这样的数组,值为


另一个是使用一个包,比如,它是专门为熊猫框架设计的。我强烈推荐Seaborn,总体来说,它是一个非常漂亮和设计良好的包。例如,它有自己的版本,支持
DataFrame
s和一系列选项。

我可以通过将
values
在每个系列之后:
df[df.Scenario=='S1'][“LMP”].值
。感谢@bnaecker的解释和解决方案,效果非常好!不过更好的是,你帮助我发现了Seaborn,我明白你为什么推荐它。非常感谢你的帮助。
Int64Index([8, 20, 25, 27, 28, 35, 52, 57, 62, 68, 72, 74, 77, 80, 81, 83, 97], dtype='int64')