【问题标题】:Error in pandas "AttributeError: 'numpy.ndarray' object has no attribute 'set_title'"熊猫“AttributeError:'numpy.ndarray'对象没有属性'set_title'”中的错误
【发布时间】:2017-09-12 16:01:34
【问题描述】:

我有一个数据框,我想使用 pandas 将名为相似度的列绘制成直方图。这是我在 ipython 中使用的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline throws an error but why?
%matplotlib auto

Df = pd.read_csv('file1.csv')
file1_hist = Df.hist(column= 'similarity', bins =50, color= 'red')
#setting labels for title and axes throws an error, why?
file1_hist.set_title('File 1 Histogram')
file1_hist.set_xlabel('similarity(%)')
file1_hist.set_ylabel('Frequency')

首先,我无法输入“%matplotlib inline”。错误为 UnknownBackend: No event loop integration for u'inline'. Supported event loops are: qt, qt4, qt5, gtk, gtk2, gtk3, tk, wx, pyglet, glut, osx 因此,我输入了 '%matplotlib auto' 但我不确定这是否正确。

另外,当我尝试添加标题/x/y 轴名称时,我收到一条错误消息:AttributeError: 'numpy.ndarray' object has no attribute 'set_title'

有人可以帮我解决这是怎么回事吗?

谢谢。

【问题讨论】:

    标签: pandas histogram


    【解决方案1】:

    DataFrame.hist() 返回一个轴数组,因为如果您有多个列并且不使用column 参数过滤它们,DataFrame.hist 将绘制多个子图 - 每列一个。每个子图都有自己的轴:

    In [266]: df = pd.DataFrame(np.random.randint(5, size=(5, 3)), columns=list('abc'))
    
    In [267]: df
    Out[267]:
       a  b  c
    0  4  1  0
    1  4  0  0
    2  4  4  1
    3  1  0  4
    4  2  0  1
    
    In [268]: axes = df.hist(column='a', bins =50, color= 'red')
    
    In [269]: axes
    Out[269]: array([[<matplotlib.axes._subplots.AxesSubplot object at 0x0000000012167908>]], dtype=object)
    
    In [270]: axes.shape
    Out[270]: (1, 1)
    
    In [271]: type(axes)
    Out[271]: numpy.ndarray
    
    In [272]: type(axes[0][0])
    Out[272]: matplotlib.axes._subplots.AxesSubplot
    

    所以试试这个而不是你的代码:

    file1_hist[0][0].set_title('File 1 Histogram')
    file1_hist[0][0].set_xlabel('similarity(%)')
    file1_hist[0][0].set_ylabel('Frequency')
    

    【讨论】:

    • 感谢您的回复。但是,由于我已将列指定为“相似性”,所以我不应该得到子图,不是吗?我也只看到 1 个图表作为输出?
    • @Natasha,请检查我在回答中提供的示例(演示)-我还在为单列绘制直方图-a。但是DataFrame.hist() 返回了一个二维 array 轴...
    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 2020-12-03
    • 2020-11-29
    • 2020-10-06
    • 2018-01-25
    • 2016-06-29
    • 2020-03-25
    • 2013-12-07
    相关资源
    最近更新 更多