@MaxNoe已经用zip和enumerate很优雅地回答了这个问题。但是,对于不熟悉zip和enumerate的用户,以下代码可以达到预期的结果:import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
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.3]]
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]]
xval = [0.,1.,2.] #The places where the ticks are going to be on the x-axis
bottom_append = 0 #Counter to keep track of the bar (this is quite important)
fig = plt.figure(figsize=(5,5))
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:
if x==0:
print(status_day1[x][y], bottom_append)
ax.bar(0, status_day1[x][y], width = 0.3, color='blue',align='center')
bottom_append = bottom_append+status_day1[x][y]
else:
print(status_day1[x][y], bottom_append)
ax.bar(0, status_day1[x][y], width = 0.3, color='blue',align='center',bottom=bottom_append)
bottom_append = bottom_append+status_day1[x][y]
elif y==1:
print(status_day1[x][y], bottom_append)
ax.bar(0, status_day1[x][y], width = 0.3, color='red',align='center', bottom=bottom_append)
bottom_append = bottom_append+status_day1[x][y]
else:
print(status_day1[x][y], bottom_append)
ax.bar(0, status_day1[x][y], width = 0.3, color='green',align='center', bottom=bottom_append)
bottom_append = bottom_append+status_day1[x][y]
bottom_append = 0
# Code is exactly same as the above, only takes into account day2
for x in range(0,4): #Looping through every hour
for y in range(0,3): #Looping through every parameter
if y==0:
if x==0:
print(status_day2[x][y], bottom_append)
ax.bar(1, status_day2[x][y], width = 0.3, color='blue',align='center')
bottom_append = bottom_append+status_day2[x][y]
else:
print(status_day2[x][y], bottom_append)
ax.bar(1, status_day2[x][y], width = 0.3, color='blue',align='center',bottom=bottom_append)
bottom_append = bottom_append+status_day2[x][y]
elif y==1:
print(status_day2[x][y], bottom_append)
ax.bar(1, status_day2[x][y], width = 0.3, color='red',align='center', bottom=bottom_append)
bottom_append = bottom_append+status_day2[x][y]
else:
print(status_day2[x][y], bottom_append)
ax.bar(1, status_day2[x][y], width = 0.3, color='green',align='center', bottom=bottom_append)
bottom_append = bottom_append+status_day2[x][y]
# Setting the properties of the subplot in an attempt to beautify it
Label1 = mpatches.Patch(color='blue', label='Label1')
Label2 = mpatches.Patch(color='green', label='Label2')
Label3 = mpatches.Patch(color='red', label='Label3')
ax.legend(handles=[Label1, Label2, Label3], loc=1)
ax.set_xticks(xval)
ax.set_xticklabels(["Day1","Day2","Day3"])
ax.set_xlabel('Day')
ax.set_ylabel('Hours')
plt.show()