python - Single legend at changing categories (!) in subplots from pandas df -
roughly speaking need create 1 legend several subplots, have changing number of categories = legend entries. let me clarify bit deeper:
i have figure 20 subplots, 1 each country within spatial scope:
fig, ax = plt.subplots(nrows=4, ncols=5, sharex=true, sharey=false, figsize = (32,18))
within loop, logic group data need normal 2-dimensional pandas dataframe stats
, plot each of these 20 axes:
colors = stats.index.to_series().map(type_to_color()).tolist() stats.t.plot.bar(ax=ax[i,j], stacked=true, legend=false, color=colors)
however, stats
dataframe changing size loop loop, since not every category applies each of these countries (i.e. in 1 country there can 2 types, in there more 10). reason pre-defined specific color each type. far, creating 1 legend every subplot within loop:
ax[i,j].legend(fontsize=9, loc='upper right')
this works, blows subplots unnecessarily. how can plot 1 big legend above/below/beside these plots, since have defined according color. given approach here fig.legend(handles, labels, ...)
does not work since line handles not available pandas plot. plotting legend directly with
plt.legend(loc = 'lower center',bbox_to_anchor = (0,-0.3,1,1), bbox_transform = plt.gcf().transfigure)
shows entries last subplot, not sufficient.
any appreciated! thank much!
edit example dataframe stats
in 1 country this:
2015 2020 2025 2030 2035 2040 hydro 29.229082 28.964424 28.528139 27.120194 25.932098 24.675778 natural gas 0.926800 0.926800 0.926800 0.926800 0.003600 nan wind 25.799950 25.797550 0.776400 0.520800 0.234400 nan
whereas in country might this:
2015 2020 2025 2030 2035 bioenergy 0.033690 0.033690 0.030000 nan nan hard coal 5.307300 0.065100 0.021000 nan nan hydro 22.834454 23.930642 23.169014 21.639914 19.623791 natural gas 8.378116 8.674121 8.013598 6.755498 5.255450 solar 5.100403 5.100403 5.100403 5.100403 5.093403 wind 8.983560 8.974740 8.967240 8.378300 0.195800
here's how works legend alphabetical order without messing colors up:
import matplotlib.patches mpatches import collections fig, ax = plt.subplots(nrows=4, ncols=5, sharex=true, sharey=false, figsize = (32,18)) labels_mpatches = collections.ordereddict() a, b in enumerate(countries()) # data logic here colors = stats.index.to_series().map(type_to_color()).tolist() stats.t.plot.bar(ax=ax[i,j],stacked=true,legend=false,color=colors) # pass legend information ordereddict stats_handle, stats_labels = ax[i,j].get_legend_handles_labels() u, v in enumerate(stats_labels): if v not in labels_mpatches: labels_mpatches[v] = mpatches.patch(color=colors[u], label=v) # after loop, legend layouting. labels_mpatches = collections.ordereddict(sorted(labels_mpatches.items())) fig.legend(handles=labels_mpatches.values(),labels=labels_mpatches.keys())
Comments
Post a Comment