使用Python建立直方图。关键字不能是表达式

时间:2019-11-19 15:22:37

标签: python matplotlib

我有一组贷款pd_vector的违约概率的变量,我想为其创建直方图,但是对于python来说我是新手,不理解下面的代码背后的含义我已经取消了我的讲师。

想知道我在下面做的事情是否正确以及为什么会发生错误

import matplotlib.pyplot as plt

pd_vector = [213,23,324,435,54,657,768,879,78,23]
num_bins= 12
n, bins, patches = plt.hist(pd_vector, num_bins / alpha=0.7, n_width=0.05)
plt.grid
plt.show

  File "<ipython-input-11-eafbc0a73a47>", line 2
    n, bins, patches = plt.hist(pd_vector, num_bins / alpha=0.7, n_width=0.05)
                                          ^
SyntaxError: keyword can't be an expression

1 个答案:

答案 0 :(得分:0)

似乎有一些小错误。

  • 正如@Green Cloack Guy提到的那样,n_width不是一个选项,您的意思可能是rwidth。
  • 我相信您必须将grid称为plt.grid(True)
  • 我相信您必须将show称为plt.show()

请注意,在您的示例代码中,它应该是一个有效的示例,即包括pd_vector(您不需要全部60个元素,只需要一些最小的有效示例)以及您进行的导入。 / p>

以下代码正在运行,请尝试一下,看看它是否符合您的期望:

import matplotlib.pyplot as plt

num_bins= 12
pd_vector = [213,23,324,435,54,657,768,879,78,23]
n, bins, patches = plt.hist(pd_vector, num_bins, alpha=0.7, rwidth=0.05)
plt.grid(True)
plt.show()

编辑:

根据您对直方图后一行的要求,可以尝试使用numpyscipty软件包,如下所示:

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats

num_bins= 12
pd_vector = np.random.normal(0, 1, (1000, ))
density = stats.gaussian_kde(pd_vector)
n, bins, patches = plt.hist(pd_vector, bins=np.linspace(-6, 6, num_bins), histtype=u'step', density=True)

plt.plot(bins, density(bins))
plt.grid(True)
plt.show()

请注意,num_bins越大,结果越平滑。