使用Matplotlib创建Boxplot

时间:2017-05-22 18:23:33

标签: python pandas matplotlib boxplot

我正在使用python 3和jupyter笔记本。我有一个像这样的结构的pandas数据框:

          location  price
Apr 25   ASHEVILLE   15.0
Apr 25   ASHEVILLE   45.0
Apr 25   ASHEVILLE   50.0
Apr 25   ASHEVILLE  120.0
Apr 25   ASHEVILLE  300.0
<class 'pandas.core.frame.DataFrame'>

我只是想为每个位置创建一个箱线图,以显示每个位置的项目之间的价格范围。

当我运行以下代码时:

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline


plt.boxplot(postings)
plt.show()

它返回TypeError:unhashable type:'slice'

3 个答案:

答案 0 :(得分:4)

我猜你需要同一图表中每个位置的箱线图。 我修改了给定的数据帧,为另一个看起来像 -

的位置添加了样本数据
   date   location month  price
0    25  ASHEVILLE   Apr   15.0
1    25  ASHEVILLE   Apr   45.0
2    25  ASHEVILLE   Apr   50.0
3    25  ASHEVILLE   Apr  120.0
4    25  ASHEVILLE   Apr  300.0
5    25  NASHVILLE   Apr   34.0
6    25  NASHVILLE   Apr   55.0
7    25  NASHVILLE   Apr   70.0
8    25  NASHVILLE   Apr  105.0
9    25  NASHVILLE   Apr   85.0

现在,只需在此框架上调用boxplot并提供参数 - columnby

postings.boxplot(column='price', by='location')

enter image description here

答案 1 :(得分:1)

我猜&#34;价格&#34;是您想要使用boxplotted的数据列。因此,您需要先选择此列,并仅将该列提供给plt.boxplot

u = u"""index,location,price
    Apr 25,ASHEVILLE,15.0
    Apr 25,ASHEVILLE,45.0
    Apr 25,ASHEVILLE,50.0
    Apr 25,ASHEVILLE,120.0
    Apr 25,ASHEVILLE,300.0"""

import io
import pandas as pd
import matplotlib.pyplot as plt

data = io.StringIO(u)

df = pd.read_csv(data, sep=",", index_col=0)

plt.boxplot(df["price"])
plt.show()

enter image description here

答案 2 :(得分:0)

根据数据显示,您希望从您拥有的5个价格值中获得一个带有单个方框的箱线图。您需要传递您想要制作箱形图的实际数据。

plt.boxplot(postings["price"])

查看示例here