有没有一种干净的方法可以在Python中生成折线直方图? [英] Is there a clean way to generate a line histogram chart in Python?

查看:146
本文介绍了有没有一种干净的方法可以在Python中生成折线直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个绘制线而不是步骤图或条形图的直方图.我正在使用python 2.7下面的plt.hist函数绘制一条阶梯线,而bins在plt.plot函数中不对齐.

I need to create a histogram that plots a line and not a step or bar chart. I am using python 2.7 The plt.hist function below plots a stepped line and the bins don't line up in the plt.plot function.

import matplotlib.pyplot as plt
import numpy as np
noise = np.random.normal(0,1,(1000,1))
(n,x,_) = plt.hist(noise, bins = np.linspace(-3,3,7), histtype=u'step' )  
plt.plot(x[:-1],n)

我需要使该行与箱中心的每个箱的计数相关联,就像有一个histt​​ype = u'line'标志和align = u'mid'标志一起

I need the line to correlate with each bin's count at the bin centers as if there was a histtype=u'line' flag to go with the align=u'mid' flag

推荐答案

使用scipy,您可以估计概率密度函数:

Using scipy, you could use stats.gaussian_kde to estimate the probability density function:

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

noise = np.random.normal(0, 1, (1000, ))
density = stats.gaussian_kde(noise)
n, x, _ = plt.hist(noise, bins=np.linspace(-3, 3, 50), 
                   histtype=u'step', density=True)  
plt.plot(x, density(x))
plt.show()

这篇关于有没有一种干净的方法可以在Python中生成折线直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆