Следуя великолепному ответу @ Скотта, вы можете получить столбцы с накоплением по желанию.
import matplotlib.pyplot as plt
cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
df_out = df.unstack()
d = dict(zip(df.columns.get_level_values(0),cycle))
c = df_out.columns.get_level_values(0).map(d)
g=df_out.plot.bar(stacked=True, color=c, figsize=(10,8), edgecolor='k')
Чтобы добавить метки, вам нужно найти правильную позицию и метить итеративно.
Вот один из способовсделать это:
РЕДАКТИРОВАТЬ: только один цикл
h=0
x=0
unique_dates=df1.index.get_level_values(0).unique() # get the bars
city=df_out.iloc[x][df_out.iloc[x]!=0].dropna().index.get_level_values(1) #get the cities
for y,val in enumerate(df1.index.get_level_values(0)): #loop through the dates
if val==unique_dates[x]: #check the x position
g.text(x-0.05,1+h-0.5,"%s" % city[h])
h+=1
else: # move to next x coord, update city labels and add text for the next x coordinate (h=0)
x+=1
city=df_out.iloc[x][df_out.iloc[x]!=0].dropna().index.get_level_values(1) #get cities
g.text(x-0.05,1-0.5,"%s" % city[0])
h=1 # set h to 1 as we already printed for h=0
Исходное решение
for x ,date in enumerate(df_out.index):
h=0
city=df_out.iloc[x][df_out.iloc[x]!=0].dropna().index.get_level_values(1) #get cities
for y,val in enumerate(df.index.get_level_values(0)):
if val==date:
g.text(x,1+h-0.5,"%s" % city[h])
h+=1
else:
continue
