Matplotlib - Stepped histogram with already binned data

前端 未结 4 1663
温柔的废话
温柔的废话 2020-12-15 06:13

I am trying to get a histogram with already binned data. I have been trying to use bar() for this, but I can\'t seem to figure out how to make it a stepped hist

4条回答
  •  既然无缘
    2020-12-15 06:53

    From the accompanying source at http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html

    here is how they drew that graph:

    [snip]

    and the bit you want appears to be

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

    Edit: if you want to know how hist() works, look at the source - it's defined in matplotlib/axes.py starting at line 7407.

    Looking at line 7724,

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

    for N bars, bins is an numpy.ndarray of N+1 values, being the edges for each bar. They twin the values for each bar (this is what fraxel is doing with np.ravel below) and shift the datapoints half a bar left to center them

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

    set the height of each bar, twinned but offset by one (relative to the x values) to produce the step effect

    # 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))
    

    and the self.fill bit is what actually draws the lines.

提交回复
热议问题