Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python构建直方图。关键字can';这不是一种表达_Python_Matplotlib - Fatal编程技术网

用Python构建直方图。关键字can';这不是一种表达

用Python构建直方图。关键字can';这不是一种表达,python,matplotlib,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 / al

我有一个变量,用于一组贷款的违约概率
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
导入matplotlib.pyplot作为plt
pd_向量=[213,23324435,54657768879,78,23]
数量=12
n、 容器,贴片=plt.hist(pd_向量,数量容器/α=0.7,n_宽度=0.05)
plt.grid
节目
文件“”,第2行
n、 容器,贴片=plt.hist(pd_向量,数量容器/α=0.7,n_宽度=0.05)
^
SyntaxError:关键字不能是表达式

似乎有几个小错误

  • 正如@Green Cloack Guy提到的,n_宽度不是一个选项,您可能指的是rwidth
  • 我相信您必须将
    grid
    称为
    plt.grid(True)
  • 我相信您必须调用
    show
    as
    plt.show()
请注意,在您的示例代码中,它应该是一个工作示例,即包括
pd_vector
(您不需要所有60个元素,只需要一些最小的工作示例)和您进行的导入

以下代码正在运行,请尝试并查看是否达到预期效果:

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()
编辑:

根据您对柱状图后面一行的请求,您可以尝试使用
numpy
scipty
软件包,如下所示:

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\u bins越大,结果越平滑。

罪魁祸首是
num\u bins/alpha=0.7
。Python认为您试图传递一个参数
num\u bins/alpha
,但这是一个表达式,不是一个名称,所以它给了您一个错误。我认为问题是你需要用
/
替换
-这行吗?这里的pd_向量是什么?@GreenCoveGuy是的,谢谢你。有大量错误消息,最后一条是“未知属性n_宽度”。有没有可能这意味着什么,如果有办法我可以做得更好presentable@jkazan这是一组贷款违约概率的60个值的列表。什么模块是
plt
?再次感谢您,它工作得非常出色。有没有一种方法可以在histrogram顶部添加一条类似于正态分布曲线的线,一条沿着直方图路径的线