簡體   English   中英

Matplotlib - 已經分箱數據的階梯直方圖

[英]Matplotlib - Stepped histogram with already binned data

我正在嘗試獲取已經分箱數據的直方圖。 我一直在嘗試使用bar() ,但我似乎無法弄清楚如何從示例中將它變成像這樣的階梯直方圖,而不是填充直方圖。

在此輸入圖像描述

您可以通過抵消數據並使用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')

劇情:

在此輸入圖像描述

最簡單的解決方案是將您的分箱數據集轉換為未分箱的加權數據集(元素數= =箱數)。 未綁定的數據集將包含等於bin中心的數據值和等於每個bin中的值的權重。 例如,假設您的分箱數據是,

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

希望有所幫助!

來自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個柱子,箱子是N + 1值的numpy.ndarray,是每個柱子的邊緣。 他們將每個柱子的值孿生(這是fraxel在下面的np.ravel中所做的)並將數據點移動半個左邊的中心位置

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

設置每個條形的高度,孿生但偏移一個(相對於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位實際上是繪制線條的。

由於某種原因,我嘗試時最后一個bin沒有正確關閉。 如果顯示最后一行,從前面的答案中看不出來,所以我決定制作自己的功能,這就是我想要的。

def make_bar_contour_plot(ax,x_input,y_input):

    x = list(np.ravel(zip(x_input[:-1],x_input[:-1]+1)))[1:]
    x += [x[-1]+20] + [300] 
    y = list(np.ravel(zip(y_input,y_input))) +[0]
    ax.plot(x,y,ls='steps')

    return ax

添加的20300分別是我的binsize和end值,如果有人想要使用它,需要調整。 x_inputy_input是來自np.histogram的返回值。 我得到的圖(藍色是輪廓,用上面的函數繪制。紅色,相同數據的條形圖):

我的輪廓繪制直方圖的結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM