![](/img/trans.png)
[英]Python histogram in log space with one bin centered at a specific value
[英]How to assign a specific value to a bin in histogram in python?
親愛的計算機科學家家庭
我想知道是否可以在直方圖中將我給出的任何值分配給某個 bin。 如果您在我的代碼中注意到它會生成一個直方圖,其中包含 2 個填充數量為 1 的 bin。
# -*- coding: utf-8 -*-
"""
Created on Sat May 9 20:23:51 2020
@author: DeAngelo
"""
import matplotlib.pyplot as plt
import numpy as np
import math
fig,ax = plt.subplots(1,1)
a = np.array([11,75])
ax.hist(a, bins = [0,25,50,75,100])
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
plt.show()
首先,您能否理論上告訴計算機您要將分配的值放入 75-100 箱中。 並將其移至 0-25 bin。 這意味着我現在將在 0-25 箱中有 2 個條目。 但我的數組仍然是a=[11,75]
另一個例子是我有一個數組'b = np.array [3]',我把它畫在我的直方圖上。 我知道這將被分配到 0-25 的 bin 中,但是我可以告訴計算機將它放入 75-100 的 bin 中嗎?
如果有怎么辦?
其次,我知道你可以使用np.mean(a)
來計算平均值。 但是假設我想將該值放入對應於 75-100 的 bin 中。 那可能嗎?
我查看了這段代碼How to assign a number to a value drops in a certain bin ,但那是在古埃及象形文字中,不幸的是我的學位是物理學而不是那個。
如果你能幫助我,那對我來說意義重大。 <3
直方圖僅表示為條形圖,因此您可以操縱條形值。 在這里,您可以預先計算直方圖和 plot 它作為條形圖:
import matplotlib.pyplot as plt
import numpy as np
import math
a = np.array([11,75])
# calculate histogram values
vals, bins = np.histogram(a, bins = [0,25,50,75,100])
width = np.ediff1d(bins)
fig,ax = plt.subplots(1,1)
# plot histogram values as bar chart
ax.bar(bins[:-1] + width/2, vals, width)
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
plt.show()
這給了你你的例子。 但是,如果您願意,您現在可以在繪圖之前操縱條形值:
# the bin values
vals
>>> array([1, 0, 0, 1])
# bin edges
bins
>>> array([ 0, 25, 50, 75, 100])
# do manipulation -> remove one count from 75-100 bin and put in 0-25 bin
vals[-1] -= 1
vals[0] += 1
# plot new graph
fig,ax = plt.subplots(1,1)
# plot histogram values as bar chart
ax.bar(bins[:-1] + width/2, vals, width)
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
plt.show()
我必須評論一下,您這樣做的原因是什么? 在您的示例中,您想要計算平均值並將其放入錯誤的 bin 中。 你當然可以像我上面展示的那樣做到這一點,但我不確定這意味着什么?
是的,這是可能的。 您可以通過將其分配給變量來捕獲直方圖 function 的返回值:
h = ax.hist(a, bins = [0, 25, 50, 75, 100])
h
(array([1., 0., 0., 1.]),
array([ 0, 25, 50, 75, 100]),
<a list of 4 Patch objects>)
正如文檔所說,這是“一個元組(n,bins,patches)”。 我們只對計數和箱感興趣,所以讓我們將它們分配給各個變量:
counts, bins, _ = h
現在您可以以任何您喜歡的方式操作計數,例如將一個計數從第四個 bin 移到第一個 bin:
counts[3] -= 1
counts[0] += 1
counts
array([2., 0., 0., 0.])
我們可以將這些數據轉換為直方圖 plot,如文檔中weights
參數下所示:
plt.hist(bins[:-1], bins, weights=counts);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.