Недавно я запрограммировал функцию для выполнения чего-то очень похожего.Здесь у вас есть упрощенная версия:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.colors import colorConverter
import matplotlib.lines as mlines
import matplotlib
def _add_legend(axes):
'It adds the legend to the plot'
box = axes.get_position()
axes.set_position([box.x0, box.y0, box.width * 0.9, box.height])
handles, labels = axes.get_legend_handles_labels()
# sort by the labels
handel_lables = sorted(zip(handles, labels), key=operator.itemgetter(1))
handles, labels = zip(*handel_lables)
axes.legend(handles, labels, bbox_to_anchor=(1.05, 1), loc=2,
borderaxespad=0., prop={'size':LEGEND_FONT_SIZE},
fancybox=True, numpoints=1)
def stacked_bars(matrix, fhand, bar_colors=None):
'It draws stacked columns'
bar_width = 1
fig = Figure(figsize=FIGURE_SIZE)
canvas = FigureCanvas(fig)
axes = fig.add_subplot(111)
nrows, ncols = matrix.shape
bar_locs = range(0, nrows)
cum_heights = numpy.zeros(nrows)
for col_index, (col_name, column) in enumerate(matrix.iteritems()):
color = bar_colors[col_index] if bar_colors is not None else None
values = column.values
axes.bar(bar_locs, values, color=color, bottom=cum_heights,
width=bar_width, label=col_name)
cum_heights += values
min_y, max_y = axes.get_ylim()
#bar labels
axes.set_xticks([l + bar_width * 0.4 for l in bar_locs])
labels = axes.set_xticklabels([str(l) + ' ' for l in matrix.index.values],
fontsize=AXIS_LABELS_FONT_SIZE)
for label in labels:
label.set_rotation('vertical')
_add_legend(axes)
canvas.print_figure(fhand, format=_get_format_from_fname(fhand.name))
fhand.flush()
Я надеюсь, что это поможет вам понять.