来自 Table 的直方图

Histogram from Table

Table

你好,我正在尝试用上面的 table 制作直方图,下面是我的编码。

def histograms(t):
    salaries = t.column('Salary')
    salary_bins = np.arange(min(salaries), max(salaries)+1000, 1000)
    t.hist('Salary', bins=salary_bins, unit='$')
    
histograms(full_data)

但是显示不正确。你能帮帮我吗?

Histogram

直方图中的 bins 参数指定数据将均匀分布到的 bins 的数量。

假设您有一个这样的薪水样本数据框:

import pandas as pd

sample_dataframe = pd.DataFrame({'name':['joe','jill','martin','emily','frank','john','sue','sally','sam'],
                                 'salary':[105324,65002,98314,24480,55000,62000,75000,79000,32000]})

#output:
     name  salary
0     joe  105324
1    jill   65002
2  martin   98314
3   emily   24480
4   frank   55000
5    john   62000
6     sue   75000
7   sally   79000
8     sam   32000

如果你想绘制一个直方图,其中薪水将分布在 10 个箱子中,并且你想坚持使用你的函数,你可以这样做:

import matplotlib.pyplot as plt

def histograms(t):
    plt.hist(t.salary, bins = 10, color = 'orange', edgecolor = 'black')
    plt.xlabel('Salary')
    plt.ylabel('Count')
    plt.show()

histograms(sample_dataframe)

如果您希望 x 轴刻度反映 10 个 bin 的边界,您可以添加此行:

import numpy as np
plt.xticks(np.linspace(min(t.salary), max(t.salary), 11), rotation = 45)

最后,为了将 y 刻度显示为整数,您添加以下行:

from matplotlib.ticker import MaxNLocator
plt.gca().yaxis.set_major_locator(MaxNLocator(integer=True))

最终函数如下所示:

def histograms(t):
    plt.hist(t.salary, bins = 10, color = 'orange', edgecolor = 'black')
    plt.xlabel('Salary')
    plt.ylabel('Count')

    plt.gca().yaxis.set_major_locator(MaxNLocator(integer=True))
    plt.xticks(np.linspace(min(t.salary), max(t.salary), 11), rotation = 45)
    plt.show()

这是您要找的吗?

import matplotlib.pyplot as plt
def histograms(t):
    _min = min(t['salary'])
    _max = max(t['salary'])
    bins = int((_max - _min) / 1000) # dividing the salary range in bins of 1000 each
    plt.hist(t['salary'], bins = bins)
histograms(df)