Matplotlib-已装箱的步进直方图

2024-06-07 09:52:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到一个已经装箱的数据的柱状图。我一直在尝试使用bar()来实现这一点,但是我似乎不知道如何使它成为阶梯直方图like this one from the examples,而不是填充直方图。

enter image description here


Tags: the数据frombar直方图thisoneexamples
3条回答

http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html的附带来源

下面是他们如何绘制的图表:

[剪]

你想要的是

pylab.hist(x, bins=bins, histtype='step')
                            ^
                        right here

编辑:如果您想知道hist()是如何工作的,请查看源代码-它是在matplotlib/axes.py中从第7407行开始定义的。

看7724号线

x = np.zeros( 2*len(bins), np.float )
y = np.zeros( 2*len(bins), np.float )

对于N个条,bins是N+1值的numpy.ndarray,是每个条的边。它们将每个条的值双倍化(这是fraxel对下面的np.ravel所做的),并将数据点左移半条使其居中

x[0::2], x[1::2] = bins, bins
x -= 0.5*(bins[1]-bins[0])

设置每个条的高度,成对但偏移1(相对于x值),以产生阶跃效果

# n is an array of arrays containing the number of items per bar
patches = []    # from line 7676
for m, c in zip(n, color):
    y[1:-1:2], y[2::2] = m, m
    patches.append(self.fill(x, y, closed=False, edgecolor=c, fill=False))

self.fill位实际上是画线的。

您可以通过偏移数据并使用plot来作弊:

from matplotlib import pyplot
import numpy as np

#sample data:
x = np.arange(30)
y = np.cumsum(np.arange(30))
#offset the x for horizontal, repeat the y for vertical:
x = np.ravel(zip(x,x+1))
y = np.ravel(zip(y,y))

pyplot.plot(x,y)
pyplot.savefig('plt.png')

情节:

enter image description here

最简单的解决方案是将已装箱的数据集转换为未装箱的加权数据集(元素数=箱数)。未绑定的数据集将由等于bin中心的数据值和等于每个bin中的值的权重组成。例如,假设你的binned数据是

binedges = [0.0, 1.0, 2.0, 3.0]
ybinned = [11., 22., 33.]

相应的加权数据集是

y =       [0.5, 1.5, 2.5]
weights = [11., 22., 33.]

请注意,使用bin中心的选择是任意的,可以使用bin中的任何点。一旦生成了未装箱的数据集,就可以使用标准的matplotlib直方图绘制(即Axes.hist)。

python中的一个示例实现如下:

def plot_binned_data(axes, binedges, data,
               *args, **kwargs):
    #The dataset values are the bin centres
    x = (binedges[1:] + binedges[:-1]) / 2.0
    #The weights are the y-values of the input binned data
    weights = data
    return axes.hist(x, bins=binedges, weights=weights,
               *args, **kwargs)

现在您可以完全访问所有Axes.Histogram绘图选项,包括histtype="step"来创建所需的阶梯直方图。

使用这个函数的一个例子是

import numpy
import matplotlib.pyplot as plt

#Create a dataset
dataset = numpy.random.normal(size=100)
#Bin the dataset
binedges = numpy.linspace(-5.0, 5.0, num=10)
y, binedges = numpy.histogram(dataset, binedges)

#Plot the dataset
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plot_binned_data(ax, binedges, y, histtype="step")
plt.show()

希望能有帮助!

相关问题 更多 >

    热门问题