我正在嘗試從 2 個串列創建一個堆疊條形圖:
counts_start = [tensor(0.),
tensor(0.),
tensor(0.0050),
tensor(0.0100),
tensor(0.2833),
tensor(0.8250),
tensor(0.8917),
tensor(1.),
tensor(1.),
tensor(1.)]
counts_end = [tensor(0.1350),
tensor(0.1467),
tensor(0.1517),
tensor(0.2233),
tensor(0.2350),
tensor(0.2417),
tensor(0.4100),
tensor(0.4200),
tensor(0.4483),
tensor(0.4600)]
在
每個串列都有一個概率值,因此最大值為 1,最小值為 0,這是我需要條形圖開始和結束但無法正常作業的地方。另請注意,第三列和第四列頂部是藍色,這使得藍色看起來具有更高的價值(事實并非如此)。
我還嘗試將第二plt.bar行替換為plt.bar(indices_start,[a_i - b_i for a_i, b_i in zip(counts_start, counts_end)], bottom=counts_end)輸出

這幾乎是正確的(最大值為 1),除了前幾列的顏色錯誤(我認為這是因為負值)。
為了澄清,我希望 2 個串列之間的每一列的最大值是該列的最大值。如果counts_start串列中有較高的值,則藍色應在其值的頂部(例如 0.8917),而較小的值應為其值的最大值(例如 0.4100)。所以它看起來像一列,紅色為 0-0.4100,藍色為 0.4100-0.8917。但是,如果counts_end串列中有更高的值(例如 0.1517),則該列的頂部應為紅色,該列的頂部為 0.1517,而藍色應為其對應的值(例如 0.0050)。它看起來像一列,藍色為 0-0.0050,紅色為 0.0050-0.1517。
uj5u.com熱心網友回復:
如果我理解正確,您希望標準化您的串列值,以便counts_start[i] counts_end[i] == 1.
這可以通過以下方式完成:
start = [0, 0, 0.005, 0.01, 0.2833, 0.825, 0.8917, 1, 1, 1]
end = [0.135, 0.1467, 0.1517, 0.2233, 0.235, 0.2417, 0.41, 0.42, 0.4483, 0.46]
new_start, new_end = [], []
for x, y in zip(start, end):
t = x y
new_start.append(x / t)
new_end.append(y / t)
n = len(start)
plt.bar(range(n), new_end, color="r")
plt.bar(range(n), new_start, bottom=new_end)
plt.show()
這會產生以下情節:

編輯:好的,為此我相信您將需要跟蹤 4 個串列,如下所示:
start = [0, 0, 0.005, 0.01, 0.2833, 0.825, 0.8917, 1, 1, 1]
end = [0.135, 0.1467, 0.1517, 0.2233, 0.235, 0.2417, 0.41, 0.42, 0.4483, 0.46]
lo_start, hi_start, lo_end, hi_end = [], [], [], []
for x, y in zip(start, end):
if x > y:
a, b, c, d = 0, x - y, y, 0
else:
a, b, c, d = x, 0, 0, y - x
lo_start.append(a)
hi_start.append(b)
lo_end.append(c)
hi_end.append(d)
n = len(start)
offset = [max(x, y) for x, y in zip(lo_start, lo_end)]
plt.bar(range(n), lo_start, color="tab:blue")
plt.bar(range(n), lo_end, color="tab:red")
plt.bar(range(n), hi_start, bottom=offset, color="tab:blue")
plt.bar(range(n), hi_end, bottom=offset, color="tab:red")
plt.show()
產生:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/415774.html
標籤:
