英文:
Stacked bar charts with differing x axes
问题
我正在使用matplotlib创建一个堆叠柱状图。
我有多个要绘制的数组,但为了这个问题的简化,我将其简化为2个。
rates = [4, 4.1, 4.2, 4.3, 4.4, 4.5]
counts = [12, 17, 22, 9, 12, 18]
rates1 = [4.3, 4.4]
counts1 = [24, 17]
我想要绘制一个rates与counts的柱状图,其中rates1的柱状图叠加在其上。
由于数组大小不匹配,我遇到了错误。
我认为我需要填充rates中“缺失”的部分,例如4.1,用零值填充。但我不想硬编码这个。我也不能只在列表末尾填充零,因为这样计数就不会与正确的速率对齐。
英文:
I am using matplotlib to create a stacked barchart.
I have multiple arrays to plot but will simplify it to 2 for the sake of this questions.
rates = [4, 4.1, 4.2, 4.3, 4.4, 4.5]
counts = [12, 17, 22, 9, 12, 18]
rates1 = [4.3, 4.4]
counts1 = [24, 17]
I want to plot a barchart for rates against counts, with the rates1 bar stacked above it.
I am getting an error due to the mismatched size of the arrays.
I believe I need to fill in where the rates are "missing", eg. 4.1, with a zero value. But don't want to hardcode this. I also can't just pad the end of the list with zeroes as then the counts won't align with the correct rate.
答案1
得分: 1
你可以使用字典来存储数组,然后使用字典推导式填充缺失的数据点:
data = dict(zip(rates, counts))
data
# {4: 12, 4.1: 17, 4.2: 22, 4.3: 9, 4.4: 12, 4.5: 18}
data1 = dict(zip(rates1, counts1))
data1
# {4.3: 24, 4.4: 17}
data1 = {k: data1[k] if k in data1 else 0 for k in data}
data1
# {4: 0, 4.1: 0, 4.2: 0, 4.3: 24, 4.4: 17, 4.5: 0}
要访问数据,你可以使用 dict.keys()
(用于获取rates)和 dict.values()
(用于获取counts)方法。
英文:
You could use dictionaries for the arrays and then use a dict comprehension to pad the missing data points:
data = dict(zip(rates, counts)
data
>>> {4: 12, 4.1: 17, 4.2: 22, 4.3: 9, 4.4: 12, 4.5: 18}
data1 = dict(zip(rates1, counts1)
data1
>>> {4.3: 24, 4.4: 17}
data1 = {k: data1[k] if k in data1 else 0 for k in data}
data1
>>> {4: 0, 4.1: 0, 4.2: 0, 4.3: 24, 4.4: 17, 4.5: 0}
To access the data, you can use the dict.keys()
(for the rates) and the dict.values()
(for the counts) methods.
Edit:
As commented by colidyre, you don't need the .keys()
method when iterating over dictionaries. So I removed it from my answer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论