[英]Convert a list of 3-Tuples in to list of list for a matplot stacked bar chart
I have a list of 3 tuples to a bin packing problem solution that looks like this:我有一个包含 3 个元组的装箱问题解决方案的列表,如下所示:
sorted_sol = [(0, 1, 170), (1, 1, 250), (2, 1, 250), (3, 1, 62), (3, 2, 30), (4, 1, 62), (4, 3, 62), (5, 2, 122), (6, 1, 212)]
As an example the first 3-Tuple means from length 0 cut 1 @ 170例如,第一个 3-Tuple 表示从长度 0 到 1 @ 170
I am trying to convert a list of 3-Tuples in to list of list for a matplot stacked bar chart but am struggling with the loop logic.我正在尝试将 3-Tuples 列表转换为 matplot 堆叠条形图的列表列表,但我正在努力处理循环逻辑。 The result should be.
结果应该是。
import matplotlib.pyplot as plt
import numpy as np
bars = list(set([int(i[0]) for i in sorted_sol]))
#loop logic here to end up with data
b1 = [170, 250, 250, 62, 62, 122, 212]
b2 = [0, 0, 0, 30, 62, 122, 0]
b3 = [0, 0, 0, 30, 62, 0, 0]
b4 = [0, 0, 0, 0, 62, 0, 0]
data =[b1, b2, b3, b4]
for c in range(0, 3):
if c == 0:
plt.bar(bars, data[c])
else:
plt.bar(bars, data[c], bottom=data[c-1])
plt.show()
Additionally the bottom property doesn't seem to be working for me, in that it doesn't appear to stack the bars 3 & 4 correctly.此外,底部属性似乎对我不起作用,因为它似乎没有正确堆叠条 3 和 4。
I'm not following your logic from sorted_sol
to the list b1,b2,b3,b4
.我没有遵循从
sorted_sol
到列表b1,b2,b3,b4
的逻辑。 It seems strange to me since your sorted_sol
only has 3
values of 62
but data
has 5 such values.这对我来说似乎很奇怪,因为您的
sorted_sol
只有3
个62
值,但data
有 5 个这样的值。
Any how, once you get to data
, you can consider using pandas
for stacked bar functionality:无论如何,一旦获得
data
,您可以考虑使用pandas
来实现堆叠条形功能:
import pandas as pd
df = pd.DataFrame(data).T
df.plot.bar(stacked=True)
Output: Output:
b
listb
列表
b
listb
列表中的索引Best that I could see but doesn't seem to fit the list-of-tuple and the b
lists我能看到的最好的,但似乎不适合元组列表和
b
列表
IIUC, something like this should work IIUC,这样的东西应该可以
dx = max(x[0] for x in sorted_sol) + 1
predata = []
for x in range(dx):
col_data = [tup[1:] for tup in sorted_sol if tup[0] == x]
temp = [n * [y] for n, y in col_data]
predata.append([i for sublist in temp for i in sublist])
dy = max(len(x) for x in predata)
data = [[i.pop() if i else 0 for i in predata] for _ in range(dy)]
Output: Output:
[[170, 250, 250, 30, 62, 122, 212],
[0, 0, 0, 30, 62, 122, 0],
[0, 0, 0, 62, 62, 0, 0],
[0, 0, 0, 0, 62, 0, 0]]
The reason your plot doesn't work is because bottom
needs to be the cumulative sum of the data.您的 plot 不起作用的原因是因为
bottom
需要是数据的累积总和。 Try something like:尝试类似:
bottom = 7 * [0]
for i in range(4):
plt.bar(range(7), data[c], bottom=bottom)
bottom = [sum([a, b]) for a, b in zip(data[c], bottom)]
If you use numpy, the addition on the last line can simply be data[i] + bottom
如果使用 numpy,最后一行的加法可以简单地为
data[i] + bottom
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.