使用Matplotlib创建箱线图

10

我正在使用 Python 3 和 Jupyter Notebook。我有一个 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'。


你确定 postings 是一个数据框吗?尝试只传递列的值而不是整个数据框。 - Paul H
这是一个数据框。当我尝试传递plt.boxplot(postings.location)时,它会输出IndexError: 0。 - Keenan Burke-Pitts
3个回答

13
我猜你需要在同一图表中为每个地点提供箱线图。我修改了给定的数据框以添加另一个位置的示例数据,看起来像-
   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')

输入图片说明


3

我猜“price”是你想要绘制箱线图的数据列。因此,你需要先选择这一列,并将只有该列的数据提供给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


1
根据数据,您希望从5个价格值中得到一个箱线图,只有一个框。您需要传递要制作箱线图的实际数据。
plt.boxplot(postings["price"])

查看示例这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接