gpt4 book ai didi

python - 使用 python 3 中的 matplotlib 在堆叠条形图中堆叠多列

转载 作者:太空宇宙 更新时间:2023-11-03 16:41:35 30 4
gpt4 key购买 nike

我正在尝试生成一个堆积条形图来跟踪多天内每小时的三个参数。样例图为SamplePlot 。然而,我在 python 中绘制这个图并没有成功。事实上,我是 python 的初学者,这让事情变得更糟。

之前为回答此问题所做的两次尝试是:Horizontal stacked bar chart in Matplotlibstack bar plot in matplotlib and add label to each section (and suggestions) 。但是,按照上述任何解决方案,我都无法达到预期的结果。

任何人都可以为我提供有关如何生成情节的指导或为我指明方向吗?

编辑1:我写的代码如下:

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

status_day1 = [[0.2,0.3,0.5], [0.1,0.3,0.6], [0.4,0.4,0.2], [0.6,0.1,0.4]]
status_day2 = [[0.1,0.2,0.7], [0.3,0.2,0.5], [0.1,0.5,0.4], [0.2,0.5,0.3]]

day = ('Day1', 'Day2')

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)
for x in range(0,4): #Looping through every hour
for y in range(0,3): #Looping through every parameter
if y==0:
ax.bar(1, status_day1[x][y],color='b',align='center')
elif y==1:
ax.bar(1, status_day1[x][y],color='r',align='center')
else:
ax.bar(1, status_day1[x][y],color='g',align='center')
# I am assuming that the three parameters for every hour are getting stacked on top of one another
for x in range(0,4):
for y in range(0,3):
if y==0:
ax.bar(1, status_day2[x][y],color='b',align='center')
elif y==1:
ax.bar(1, status_day2[x][y],color='r',align='center')
else:
ax.bar(1, status_day2[x][y],color='g',align='center')

ax.set_xticklabels(day)
ax.set_xlabel('Day')
ax.set_ylabel('Hours')
plt.show()

我得到的不想要的结果是:Incorrect plot

最佳答案

您需要跟踪条形图的底部,请参阅 matplotlib 文档中的堆积条形图示例: http://matplotlib.org/examples/pylab_examples/bar_stacked.html

此外,您还可以使用 python 的 zipenumerate 函数以及

for value in data:
print(value)

而不是

for i in range(len(data)):
print(data[i])

这样我就得到了预期的结果:

import matplotlib.pyplot as plt

status_day1 = [
[0.2, 0.3, 0.5],
[0.1, 0.3, 0.6],
[0.4, 0.4, 0.2],
[0.6, 0.1, 0.4],
]

status_day2 = [
[0.1, 0.2, 0.7],
[0.3, 0.2, 0.5],
[0.1, 0.5, 0.4],
[0.2, 0.5, 0.3],
]

days = ('Day1', 'Day2')

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(1, 1, 1)

for day, data in enumerate((status_day1, status_day2)):
bottom = 0
for hour in data: # Looping through every hour
for value, color in zip(hour, ('b', 'r', 'g')):
ax.bar(
day,
value,
bottom=bottom,
color=color,
align='center',
)
bottom += value


ax.set_xticks([0, 1])
ax.set_xticklabels(days)
ax.set_xlabel('Day')
ax.set_ylabel('Hours')
plt.show()

关于python - 使用 python 3 中的 matplotlib 在堆叠条形图中堆叠多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36727503/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com