使用Matplotlib创建Boxplot

2024-04-26 05:00:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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:unshable type:'slice'


Tags: 数据coreimportpandasmatplotlibas笔记本jupyter
1条回答
网友
1楼 · 发布于 2024-04-26 05:00:26

我想你需要在同一张图中为每个位置绘制方框图。 我修改了给定的dataframe以添加另一个位置的示例数据,该位置看起来像-

   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

网友
2楼 · 发布于 2024-04-26 05:00:26

从数据上看,你想要一个盒子图,其中有一个盒子是你拥有的5个价格值中的一个。您需要传递要从中生成boxplot的实际数据。

plt.boxplot(postings["price"])

查看示例here

网友
3楼 · 发布于 2024-04-26 05:00:26

我猜“price”是您想要绘制boxprint的数据列。因此,您需要首先选择此列并仅将该列提供给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

相关问题 更多 >

    热门问题