'Generate graphs from plugins history.
Return the number of output files generated by the function.'

def generate_graph(self, stats):

    if (not self.graph_enabled()):
        return 0
    index_all = 0
    for p in stats.getAllPlugins():
        h = stats.get_plugin(p).get_export_history()
        ih = stats.get_plugin(p).get_items_history_list()
        if ((h is None) or (ih is None)):
            continue
        plt.clf()
        index_graph = 0
        handles = []
        labels = []
        for i in ih:
            if (i['name'] in iterkeys(h)):
                logger.debug(('Generate    graph:    %s    %s' % (p, i['name'])))
                index_graph += 1
                handles.append(plt.Rectangle((0, 0), 1, 1, fc=self.get_graph_color(i), ec=self.get_graph_color(i), linewidth=2))
                labels.append(self.get_graph_legend(i))
                plt.ylabel(self.get_graph_yunit(i, pre_label=''))
                plt.grid(True)
                (x, y) = zip(*h[i['name']])
                plt.plot_date(x, y, fmt='', drawstyle='default', linestyle='-', color=self.get_graph_color(i), xdate=True, ydate=False)
                if (index_graph == 1):
                    plt.title(p.capitalize())
            else:
                stats_history_filtered = sorted([key for key in iterkeys(h) if key.endswith(('_' + i['name']))])
                logger.debug(('Generate    graphs:    %s    %s' % (p, stats_history_filtered)))
                if (len(stats_history_filtered) > 0):
                    plt.clf()
                    index_item = 0
                    for k in stats_history_filtered:
                        index_item += 1
                        plt.subplot(len(stats_history_filtered), 1, index_item)
                        plt.ylabel(self.get_graph_yunit(i, pre_label=k))
                        plt.grid(True)
                        (x, y) = zip(*h[k])
                        plt.plot_date(x, y, fmt='', drawstyle='default', linestyle='-', color=self.get_graph_color(i), xdate=True, ydate=False)
                        if (index_item == 1):
                            plt.title(((p.capitalize() + '    ') + i['name']))
                    fig = plt.gcf()
                    fig.set_size_inches(20, (5 * index_item))
                    plt.xlabel('Date')
                    plt.savefig(os.path.join(self.output_folder, ('glances_%s_%s.png' % (p, i['name']))), dpi=72)
                    index_all += 1
        if (index_graph > 0):
            fig = plt.gcf()
            fig.set_size_inches(20, 10)
            plt.legend(handles, labels, loc=1, prop={'size': 9})
            plt.xlabel('Date')
            plt.savefig(os.path.join(self.output_folder, ('glances_%s.png' % p)), dpi=72)
            index_all += 1
        plt.close()
    return index_all
