【问题标题】:Creating a Boxplot with Matplotlib使用 Matplotlib 创建箱线图
【发布时间】:2017-10-22 12:17:18
【问题描述】:

我正在使用 python 3 和 jupyter notebook。我有一个结构如下的熊猫数据框:

          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 是一个数据框吗?尝试只传递列的值而不是整个数据框。
  • 这是一个df。当我尝试传递 plt.boxplot(postings.location) 时,它输出 IndexError: 0

标签: python pandas matplotlib boxplot


【解决方案1】:

从数据来看,您想要一个箱线图,其中包含您拥有的 5 个价格值中的一个框。您需要传递要从中制作箱线图的实际数据。

plt.boxplot(postings["price"])

查看示例here

【讨论】:

    【解决方案2】:

    我猜“价格”是您想要绘制箱线图的数据列。因此,您需要先选择该列,然后仅将该列提供给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()
    

    【讨论】:

      【解决方案3】:

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

         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')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-12
        相关资源
        最近更新 更多