예제 #1
0
    def __init__(self, data, ax, prefs, *args, **kw):

        PlotBase.__init__(self, data, ax, prefs, *args, **kw)
        if type(data) == types.DictType:
            self.gdata = GraphData(data)
        elif type(data) == types.InstanceType and data.__class__ == GraphData:
            self.gdata = data
        if self.prefs.has_key('span'):
            self.width = self.prefs['span']
        else:
            self.width = 1.0
            if self.gdata.key_type == "time":
                nKeys = self.gdata.getNumberOfKeys()
                self.width = (max(self.gdata.all_keys) -
                              min(self.gdata.all_keys)) / nKeys

        # Setup the colormapper to get the right colors
        self.cmap = None

        max_value = prefs.get('normalization')
        if max_value:
            self.cmap = cm.YlGnBu
        else:
            max_value = 100
            self.cmap = cm.RdYlGn

        self.norms = Normalize(0, max_value)
        mapper = cm.ScalarMappable(cmap=self.cmap, norm=self.norms)

        def get_alpha(*args, **kw):
            return 1.0

        mapper.get_alpha = get_alpha
        self.mapper = mapper
예제 #2
0
    def __init__(self, data, ax, prefs, *args, **kw):

        PlotBase.__init__(self, data, ax, prefs, *args, **kw)
        if type(data) == types.DictType:
            self.gdata = GraphData(data)
        elif type(data) == types.InstanceType and data.__class__ == GraphData:
            self.gdata = data
        if self.prefs.has_key('span'):
            self.width = self.prefs['span']
        else:
            self.width = 1.0
            if self.gdata.key_type == "time":
                nKeys = self.gdata.getNumberOfKeys()
                self.width = (max(self.gdata.all_keys) -
                              min(self.gdata.all_keys)) / nKeys

        # Setup the colormapper to get the right colors
        self.cmap = LinearSegmentedColormap('quality_colormap', cdict, 256)
        #self.cmap = cm.RdYlGn
        self.norms = normalize(0, 100)
        mapper = cm.ScalarMappable(cmap=self.cmap, norm=self.norms)
        mapper = cm.ScalarMappable(cmap=cm.RdYlGn, norm=self.norms)

        def get_alpha(*args, **kw):
            return 1.0

        mapper.get_alpha = get_alpha
        self.mapper = mapper
예제 #3
0
    def __init__(self, data, ax, prefs, *args, **kw):

        PlotBase.__init__(self, data, ax, prefs, *args, **kw)
        if isinstance(data, dict):
            self.gdata = GraphData(data)
        elif isinstance(data, type) and data.__class__ == GraphData:
            self.gdata = data
        if "span" in self.prefs:
            self.width = self.prefs["span"]
        else:
            self.width = 1.0
            if self.gdata.key_type == "time":
                nKeys = self.gdata.getNumberOfKeys()
                self.width = (max(self.gdata.all_keys) -
                              min(self.gdata.all_keys)) / nKeys

        # redefine the look of the scale if requested
        if isinstance(self.prefs["scale_data"], dict):
            self.cbBoundaries = list()
            self.cbValues = list()

            # ColorbarBase needs sorted data
            for boundary in sorted(self.prefs["scale_data"]):
                self.cbBoundaries.append(boundary)
                self.cbValues.append(self.prefs["scale_data"][boundary])
        else:
            self.cbBoundaries = None  # set default values
            self.cbValues = None

        if isinstance(self.prefs["scale_ticks"], list):
            self.cbTicks = self.prefs["scale_ticks"]
        else:
            self.cbTicks = None  # set default value

        # Setup the colormapper to get the right colors
        self.cmap = None

        max_value = prefs.get("normalization")
        if max_value:
            self.cmap = cm.YlGnBu  # pylint: disable=no-member
        else:
            max_value = 100
            self.cmap = cm.RdYlGn  # pylint: disable=no-member

        self.norms = Normalize(0, max_value)
        mapper = cm.ScalarMappable(cmap=self.cmap, norm=self.norms)

        def get_alpha(*args, **kw):
            return 1.0

        mapper.get_alpha = get_alpha
        self.mapper = mapper
예제 #4
0
    def __init__(self, data, ax, prefs, *args, **kw):

        PlotBase.__init__(self, data, ax, prefs, *args, **kw)
        if type(data) == types.DictType:
            self.gdata = GraphData(data)
        elif type(data) == types.InstanceType and data.__class__ == GraphData:
            self.gdata = data
        if self.prefs.has_key("span"):
            self.width = self.prefs["span"]
        else:
            self.width = 1.0
            if self.gdata.key_type == "time":
                nKeys = self.gdata.getNumberOfKeys()
                self.width = (max(self.gdata.all_keys) - min(self.gdata.all_keys)) / nKeys

        # Setup the colormapper to get the right colors
        self.cmap = None

        max_value = prefs.get("normalization")
        if max_value:
            self.cmap = cm.YlGnBu
        else:
            max_value = 100
            self.cmap = cm.RdYlGn

        self.norms = Normalize(0, max_value)
        mapper = cm.ScalarMappable(cmap=self.cmap, norm=self.norms)

        def get_alpha(*args, **kw):
            return 1.0

        mapper.get_alpha = get_alpha
        self.mapper = mapper
예제 #5
0
  def __init__( self, data, ax, prefs, *args, **kw ):

    PlotBase.__init__( self, data, ax, prefs, *args, **kw )
    if type( data ) == types.DictType:
      self.gdata = GraphData( data )
    elif type( data ) == types.InstanceType and data.__class__ == GraphData:
      self.gdata = data
    if self.prefs.has_key( 'span' ):
      self.width = self.prefs['span']
    else:
      self.width = 1.0
      if self.gdata.key_type == "time":
        nKeys = self.gdata.getNumberOfKeys()
        self.width = ( max( self.gdata.all_keys ) - min( self.gdata.all_keys ) ) / nKeys

    # Setup the colormapper to get the right colors
    self.cmap = LinearSegmentedColormap( 'quality_colormap', cdict, 256 )
    #self.cmap = cm.RdYlGn
    self.norms = normalize( 0, 100 )
    mapper = cm.ScalarMappable( cmap = self.cmap, norm = self.norms )
    mapper = cm.ScalarMappable( cmap = cm.RdYlGn, norm = self.norms )
    def get_alpha( *args, **kw ):
      return 1.0
    mapper.get_alpha = get_alpha
    self.mapper = mapper
예제 #6
0
  def __init__( self, data, ax, prefs, *args, **kw ):

    PlotBase.__init__( self, data, ax, prefs, *args, **kw )
    if isinstance( data, dict ):
      self.gdata = GraphData( data )
    elif isinstance( data, type ) and data.__class__ == GraphData:
      self.gdata = data
    if self.prefs.has_key( 'span' ):
      self.width = self.prefs['span']
    else:
      self.width = 1.0
      if self.gdata.key_type == "time":
        nKeys = self.gdata.getNumberOfKeys()
        self.width = ( max( self.gdata.all_keys ) - min( self.gdata.all_keys ) ) / nKeys

    # Setup the colormapper to get the right colors
    self.cmap = None

    max_value = prefs.get( 'normalization' )
    if max_value:
      self.cmap = cm.YlGnBu #pylint: disable=no-member
    else:
      max_value = 100
      self.cmap = cm.RdYlGn #pylint: disable=no-member

    self.norms = Normalize( 0, max_value )
    mapper = cm.ScalarMappable( cmap = self.cmap, norm = self.norms )
    def get_alpha( *args, **kw ):
      return 1.0
    mapper.get_alpha = get_alpha
    self.mapper = mapper
예제 #7
0
    def __init__(self, data=None, axes=None, *aw, **kw):

        self.ax_contain = axes
        self.canvas = None
        self.figure = None
        if self.ax_contain:
            self.figure = self.ax_contain.get_figure()
            self.canvas = self.figure.canvas
            self.dpi = self.ax_contain.figure.get_dpi()
            self.ax_contain.set_axis_off()
        self.prefs = evalPrefs(*aw, **kw)
        self.coords = {}
        self.palette = Palette()
        if isinstance(data, dict):
            self.gdata = GraphData(data)
        elif isinstance(data, object) and data.__class__ == GraphData:
            self.gdata = data
예제 #8
0
  def __init__( self, data, ax, prefs, *args, **kw ):

    PlotBase.__init__( self, data, ax, prefs, *args, **kw )
    if isinstance( data, dict ):
      self.gdata = GraphData( data )
    elif isinstance( data, type ) and data.__class__ == GraphData:
      self.gdata = data
    if self.prefs.has_key( 'span' ):
      self.width = self.prefs['span']
    else:
      self.width = 1.0
      if self.gdata.key_type == "time":
        nKeys = self.gdata.getNumberOfKeys()
        self.width = ( max( self.gdata.all_keys ) - min( self.gdata.all_keys ) ) / nKeys

    # redefine the look of the scale if requested
    if isinstance(self.prefs['scale_data'], dict):
      self.cbBoundaries = list()
      self.cbValues = list()

      # ColorbarBase needs sorted data
      for boundary in sorted(self.prefs['scale_data'].keys()):
        self.cbBoundaries.append(boundary)
        self.cbValues.append(self.prefs['scale_data'][boundary])
    else:
      self.cbBoundaries = None # set default values
      self.cbValues = None

    if isinstance(self.prefs['scale_ticks'], list):
      self.cbTicks = self.prefs['scale_ticks']
    else:
      self.cbTicks = None # set default value

    # Setup the colormapper to get the right colors
    self.cmap = None

    max_value = prefs.get( 'normalization' )
    if max_value:
      self.cmap = cm.YlGnBu #pylint: disable=no-member
    else:
      max_value = 100
      self.cmap = cm.RdYlGn #pylint: disable=no-member

    self.norms = Normalize( 0, max_value )
    mapper = cm.ScalarMappable( cmap = self.cmap, norm = self.norms )
    def get_alpha( *args, **kw ):
      return 1.0
    mapper.get_alpha = get_alpha
    self.mapper = mapper
예제 #9
0
  def __init__( self, data = None, axes = None, *aw, **kw ):

    self.ax_contain = axes
    self.canvas = None
    self.figure = None
    if self.ax_contain:
      self.figure = self.ax_contain.get_figure()
      self.canvas = self.figure.canvas
      self.dpi = self.ax_contain.figure.get_dpi()
      self.ax_contain.set_axis_off()
    self.prefs = evalPrefs( *aw, **kw )
    self.coords = {}
    self.palette = Palette()
    if isinstance( data, dict):
      self.gdata = GraphData( data )
    elif isinstance( data, object) and data.__class__ == GraphData:
      self.gdata = data
예제 #10
0
class QualityMapGraph(PlotBase):
    """
    The BarGraph class is a straightforward bar graph; given a dictionary
    of values, it takes the keys as the independent variable and the values
    as the dependent variable.
    """
    def __init__(self, data, ax, prefs, *args, **kw):

        PlotBase.__init__(self, data, ax, prefs, *args, **kw)
        if isinstance(data, dict):
            self.gdata = GraphData(data)
        elif isinstance(data, type) and data.__class__ == GraphData:
            self.gdata = data
        if "span" in self.prefs:
            self.width = self.prefs["span"]
        else:
            self.width = 1.0
            if self.gdata.key_type == "time":
                nKeys = self.gdata.getNumberOfKeys()
                self.width = (max(self.gdata.all_keys) -
                              min(self.gdata.all_keys)) / nKeys

        # redefine the look of the scale if requested
        if isinstance(self.prefs["scale_data"], dict):
            self.cbBoundaries = list()
            self.cbValues = list()

            # ColorbarBase needs sorted data
            for boundary in sorted(self.prefs["scale_data"]):
                self.cbBoundaries.append(boundary)
                self.cbValues.append(self.prefs["scale_data"][boundary])
        else:
            self.cbBoundaries = None  # set default values
            self.cbValues = None

        if isinstance(self.prefs["scale_ticks"], list):
            self.cbTicks = self.prefs["scale_ticks"]
        else:
            self.cbTicks = None  # set default value

        # Setup the colormapper to get the right colors
        self.cmap = None

        max_value = prefs.get("normalization")
        if max_value:
            self.cmap = cm.YlGnBu  # pylint: disable=no-member
        else:
            max_value = 100
            self.cmap = cm.RdYlGn  # pylint: disable=no-member

        self.norms = Normalize(0, max_value)
        mapper = cm.ScalarMappable(cmap=self.cmap, norm=self.norms)

        def get_alpha(*args, **kw):
            return 1.0

        mapper.get_alpha = get_alpha
        self.mapper = mapper

    def draw(self):

        PlotBase.draw(self)
        self.x_formatter_cb(self.ax)

        if self.gdata.isEmpty():
            return None

        # Evaluate the bar width
        width = float(self.width)
        offset = 0.0
        if self.gdata.key_type == "time":
            width = width / 86400.0

        start_plot = 0
        end_plot = 0
        if "starttime" in self.prefs and "endtime" in self.prefs:
            start_plot = date2num(
                datetime.datetime.fromtimestamp(
                    to_timestamp(self.prefs["starttime"])))
            end_plot = date2num(
                datetime.datetime.fromtimestamp(
                    to_timestamp(self.prefs["endtime"])))

        labels = self.gdata.getLabels()
        nKeys = self.gdata.getNumberOfKeys()
        tmp_b = []
        tmp_x = []
        tmp_y = []

        self.bars = []
        labels = self.gdata.getLabels()
        nLabel = 0
        labelNames = []
        colors = []
        xmin = None
        xmax = None
        for label, _num in labels:
            labelNames.append(label)
            for key, value, _error in self.gdata.getPlotNumData(label):

                if xmin is None or xmin > (key + offset):
                    xmin = key + offset
                if xmax is None or xmax < (key + offset):
                    xmax = key + offset

                if value is not None:
                    colors.append(self.getQualityColor(value))
                    tmp_x.append(key + offset)
                    tmp_y.append(1.0)
                    tmp_b.append(float(nLabel))

            nLabel += 1

        self.bars += self.ax.bar(tmp_x,
                                 tmp_y,
                                 bottom=tmp_b,
                                 width=width,
                                 color=colors)

        dpi = self.prefs.get("dpi", 100)
        setp(self.bars, linewidth=pixelToPoint(0.5, dpi), edgecolor="#AAAAAA")

        # pivots = keys
        # for idx in range(len(pivots)):
        #    self.coords[ pivots[idx] ] = self.bars[idx]

        ymax = float(nLabel)
        self.ax.set_xlim(xmin=0.0, xmax=xmax + width + offset)
        self.ax.set_ylim(ymin=0.0, ymax=ymax)
        if self.gdata.key_type == "time":
            if start_plot and end_plot:
                self.ax.set_xlim(xmin=start_plot, xmax=end_plot)
            else:
                self.ax.set_xlim(xmin=min(tmp_x), xmax=max(tmp_x))
        self.ax.set_yticks([i + 0.5 for i in range(nLabel)])
        self.ax.set_yticklabels(labelNames)
        setp(self.ax.get_xticklines(), markersize=0.0)
        setp(self.ax.get_yticklines(), markersize=0.0)

        cax, kw = make_axes(self.ax, orientation="vertical", fraction=0.07)
        cb = ColorbarBase(cax,
                          cmap=self.cmap,
                          norm=self.norms,
                          boundaries=self.cbBoundaries,
                          values=self.cbValues,
                          ticks=self.cbTicks)
        cb.draw_all()
        # cb = self.ax.colorbar( self.mapper, format="%d%%",
        #  orientation='horizontal', fraction=0.04, pad=0.1, aspect=40  )
        # setp( cb.outline, linewidth=.5 )
        # setp( cb.ax.get_xticklabels(), size=10 )
        # setp( cb.ax.get_xticklabels(), family=self.prefs['font_family'] )
        # setp( cb.ax.get_xticklabels(), fontname = self.prefs['font'] )

    def getQualityColor(self, value):

        if value is None or value < 0.0:
            return "#FFFFFF"
        return self.mapper.to_rgba(value)

    def getLegendData(self):

        return None

    def x_formatter_cb(self, ax):
        if self.gdata.key_type == "string":
            smap = self.gdata.getStringMap()
            reverse_smap = {}
            for key, val in smap.items():
                reverse_smap[val] = key
            ticks = sorted(smap.values())
            ax.set_xticks([i + 0.5 for i in ticks])
            ax.set_xticklabels([reverse_smap[i] for i in ticks])
            # labels = ax.get_xticklabels()
            ax.grid(False)
            if self.log_xaxis:
                xmin = 0.001
            else:
                xmin = 0.0
            ax.set_xlim(xmin=xmin, xmax=len(ticks))
        elif self.gdata.key_type == "time":

            # ax.set_xlim( xmin=self.begin_num,xmax=self.end_num )
            dl = PrettyDateLocator()
            df = PrettyDateFormatter(dl)
            ax.xaxis.set_major_locator(dl)
            ax.xaxis.set_major_formatter(df)
            ax.xaxis.set_clip_on(False)
            sf = PrettyScalarFormatter()
            ax.yaxis.set_major_formatter(sf)
            # labels = ax.get_xticklabels()

        else:
            return None
예제 #11
0
파일: Graph.py 프로젝트: DIRACGrid/DIRAC
    def makeGraph(self, data, *args, **kw):

        start = time.time()

        # Evaluate all the preferences
        self.prefs = evalPrefs(*args, **kw)
        prefs = self.prefs

        if DEBUG:
            print "makeGraph time 1", time.time() - start
            start = time.time()

        if prefs.has_key("text_image"):
            self.makeTextGraph(str(prefs["text_image"]))
            return

        # Evaluate the number of plots and their requested layout
        metadata = prefs.get("metadata", {})
        plot_grid = prefs.get("plot_grid", "1:1")
        nx = int(plot_grid.split(":")[0])
        ny = int(plot_grid.split(":")[1])
        nPlots = nx * ny
        if nPlots == 1:
            if type(data) != types.ListType:
                data = [data]
            if type(metadata) != types.ListType:
                metadata = [metadata]
        else:
            if type(data) != types.ListType:
                # return S_ERROR('Single data for multiplot graph')
                print "Single data for multiplot graph"
                return
            if type(metadata) != types.ListType:
                metaList = []
                for _ in range(nPlots):
                    metaList.append(metadata)
                metadata = metaList

        # Initialize plot data
        graphData = []
        plot_prefs = []
        for i in range(nPlots):
            plot_prefs.append(evalPrefs(prefs, metadata[i]))
            gdata = GraphData(data[i])
            if i == 0:
                plot_type = plot_prefs[i]["plot_type"]
            if plot_prefs[i].has_key("sort_labels"):
                reverse = plot_prefs[i].get("reverse_labels", False)
                gdata.sortLabels(plot_prefs[i]["sort_labels"], reverse_order=reverse)
            if plot_prefs[i].has_key("limit_labels"):
                if plot_prefs[i]["limit_labels"] > 0:
                    gdata.truncateLabels(plot_prefs[i]["limit_labels"])
            if plot_prefs[i].has_key("cumulate_data"):
                gdata.makeCumulativeGraph()
            plot_title = plot_prefs[i].get("plot_title", "")
            if plot_title != "NoTitle":
                begin = ""
                end = ""
                if plot_prefs[i].has_key("starttime") and plot_prefs[i].has_key("endtime"):
                    begin = to_timestamp(plot_prefs[i]["starttime"])
                    end = to_timestamp(plot_prefs[i]["endtime"])
                elif gdata.key_type == "time":
                    begin = gdata.min_key
                    end = gdata.max_key
                if begin and end:
                    time_title = add_time_to_title(begin, end)
                    if plot_title:
                        plot_title += ":"
                    plot_prefs[i]["plot_title"] = plot_title + " " + time_title
            graphData.append(gdata)

        # Do not make legend for the plot with non-string keys (except for PieGraphs)
        if not graphData[0].subplots and graphData[0].key_type != "string" and not plot_type == "PieGraph":
            prefs["legend"] = False
        if prefs["legend"] and graphData[0].key_type != "string" and plot_type == "PieGraph":
            graphData[0].initialize(key_type="string")

        legend = Legend(graphData[0], None, prefs)
        self.figure = Figure()

        # Make Water Mark
        image = prefs.get("watermark", None)
        self.drawWaterMark(image)

        legend_ax, plot_axes = self.layoutFigure(legend)

        if DEBUG:
            print "makeGraph time layout", time.time() - start
            start = time.time()

        # Make plots
        for i in range(nPlots):
            plot_type = plot_prefs[i]["plot_type"]
            try:
                exec "import %s" % plot_type
            except ImportError, x:
                print "Failed to import graph type %s: %s" % (plot_type, str(x))
                return None

            ax = plot_axes[i]
            plot = eval("%s.%s(graphData[i],ax,plot_prefs[i])" % (plot_type, plot_type))
            plot.draw()
예제 #12
0
class PlotBase(object):
    def __init__(self, data=None, axes=None, *aw, **kw):

        self.ax_contain = axes
        self.canvas = None
        self.figure = None
        if self.ax_contain:
            self.figure = self.ax_contain.get_figure()
            self.canvas = self.figure.canvas
            self.dpi = self.ax_contain.figure.get_dpi()
            self.ax_contain.set_axis_off()
        self.prefs = evalPrefs(*aw, **kw)
        self.coords = {}
        self.palette = Palette()
        if isinstance(data, dict):
            self.gdata = GraphData(data)
        elif isinstance(data, object) and data.__class__ == GraphData:
            self.gdata = data

    def dumpPrefs(self):

        for key in self.prefs:
            print(key.rjust(20), ':', str(self.prefs[key]).ljust(40))

    def setAxes(self, axes):

        self.ax_contain = axes
        self.ax_contain.set_axis_off()
        self.figure = self.ax_contain.get_figure()
        self.canvas = self.figure.canvas
        self.dpi = self.ax_contain.figure.get_dpi()

    def draw(self):

        prefs = self.prefs
        dpi = self.ax_contain.figure.get_dpi()

        # Update palette
        palette = prefs.get('colors', {})
        if palette:
            self.palette.addPalette(palette)

        xlabel = prefs.get('xlabel', '')
        ylabel = prefs.get('ylabel', '')
        xticks_flag = prefs.get('xticks', True)
        yticks_flag = prefs.get('yticks', True)

        text_size = prefs['text_size']
        text_padding = prefs['text_padding']

        label_text_size = prefs.get('label_text_size', text_size)
        label_text_size_point = pixelToPoint(label_text_size, dpi)
        tick_text_size = prefs.get('tick_text_size', text_size)
        tick_text_size_point = pixelToPoint(tick_text_size, dpi)

        ytick_length = prefs.get('ytick_length', 7 * tick_text_size)

        plot_title = prefs.get('plot_title', '')
        if not plot_title or plot_title == 'NoTitle':
            plot_title_size = 0
            plot_title_padding = 0
        else:
            plot_title_size = prefs.get('plot_title_size', text_size)
            plot_title_padding = prefs.get('plot_text_padding', text_padding)
        plot_title_size_point = pixelToPoint(plot_title_size, dpi)

        stats_flag = prefs.get('statistics_line', False)
        stats_line = ''
        stats_line_space = 0.
        if stats_flag:
            stats_line = self.gdata.getStatString()
            stats_line_size = label_text_size
            stats_line_padding = label_text_size * 2.
            stats_line_space = stats_line_size + stats_line_padding

        plot_padding = prefs['plot_padding']
        plot_left_padding = prefs.get('plot_left_padding', plot_padding)
        plot_right_padding = prefs.get('plot_right_padding', 0)
        plot_bottom_padding = prefs.get('plot_bottom_padding', plot_padding)
        plot_top_padding = prefs.get('plot_top_padding', 0)
        frame_flag = prefs['frame']

        # Create plot axes, and set properties
        left, bottom, width, height = self.ax_contain.get_window_extent(
        ).bounds
        l, b, f_width, f_height = self.figure.get_window_extent().bounds

        # Space needed for labels and ticks
        x_label_space = 0
        if xticks_flag:
            x_label_space += tick_text_size * 1.5
        if xlabel:
            x_label_space += label_text_size * 1.5
        y_label_space = 0
        if yticks_flag:
            y_label_space += ytick_length
        if ylabel:
            y_label_space += label_text_size * 1.5

        ax_plot_rect = ( float( plot_left_padding + left + y_label_space ) / f_width,
                         float( plot_bottom_padding + bottom + x_label_space + stats_line_space ) / f_height,
                         float( width - plot_left_padding - plot_right_padding - y_label_space ) / f_width,
                         float( height - plot_bottom_padding - plot_top_padding - x_label_space - \
                                plot_title_size - 2 * plot_title_padding - stats_line_space ) / f_height )
        ax = Axes(self.figure, ax_plot_rect)
        if prefs['square_axis']:
            l, b, a_width, a_height = ax.get_window_extent().bounds
            delta = abs(a_height - a_width)
            if a_height > a_width:
                a_height = a_width
                ax_plot_rect = (
                    float(plot_left_padding + left) / f_width,
                    float(plot_bottom_padding + bottom + delta / 2.) /
                    f_height,
                    float(width - plot_left_padding - plot_right_padding) /
                    f_width,
                    float(height - plot_bottom_padding - plot_title_size -
                          2 * plot_title_padding - delta) / f_height)
            else:
                a_width = a_height
                ax_plot_rect = (
                    float(plot_left_padding + left + delta / 2.) / f_width,
                    float(plot_bottom_padding + bottom) / f_height,
                    float(width - plot_left_padding - delta) / f_width,
                    float(height - plot_bottom_padding - plot_title_size -
                          2 * plot_title_padding) / f_height)
            ax.set_position(ax_plot_rect)

        self.figure.add_axes(ax)
        self.ax = ax
        frame = ax.patch
        frame.set_fill(False)

        if frame_flag.lower() == 'off':
            self.ax.set_axis_off()
            self.log_xaxis = False
            self.log_yaxis = False
        else:
            # If requested, make x/y axis logarithmic
            if prefs.get('log_xaxis', 'False').find('r') >= 0:
                ax.semilogx()
                self.log_xaxis = True
            else:
                self.log_xaxis = False
            if prefs.get('log_yaxis', 'False').find('r') >= 0:
                ax.semilogy()
                self.log_yaxis = True
            else:
                self.log_yaxis = False

            if xticks_flag:
                setp(ax.get_xticklabels(), family=prefs['font_family'])
                setp(ax.get_xticklabels(), fontname=prefs['font'])
                setp(ax.get_xticklabels(), size=tick_text_size_point)
            else:
                setp(ax.get_xticklabels(), size=0)

            if yticks_flag:
                setp(ax.get_yticklabels(), family=prefs['font_family'])
                setp(ax.get_yticklabels(), fontname=prefs['font'])
                setp(ax.get_yticklabels(), size=tick_text_size_point)
            else:
                setp(ax.get_yticklabels(), size=0)

            setp(ax.get_xticklines(), markeredgewidth=pixelToPoint(0.5, dpi))
            setp(ax.get_xticklines(),
                 markersize=pixelToPoint(text_size / 2., dpi))
            setp(ax.get_yticklines(), markeredgewidth=pixelToPoint(0.5, dpi))
            setp(ax.get_yticklines(),
                 markersize=pixelToPoint(text_size / 2., dpi))
            setp(ax.get_xticklines(), zorder=4.0)

            line_width = prefs.get('line_width', 1.0)
            frame_line_width = prefs.get('frame_line_width', line_width)
            grid_line_width = prefs.get('grid_line_width', 0.1)
            plot_line_width = prefs.get('plot_line_width', 0.1)

            setp(ax.patch, linewidth=pixelToPoint(plot_line_width, dpi))
            #setp( ax.spines, linewidth=pixelToPoint(frame_line_width,dpi) )
            #setp( ax.axvline(), linewidth=pixelToPoint(1.0,dpi) )
            axis_grid_flag = prefs.get('plot_axis_grid', True)
            if axis_grid_flag:
                ax.grid(True,
                        color='#555555',
                        linewidth=pixelToPoint(grid_line_width, dpi))

            plot_axis_flag = prefs.get('plot_axis', True)
            if plot_axis_flag:
                # Set labels
                if xlabel:
                    t = ax.set_xlabel(xlabel)
                    t.set_family(prefs['font_family'])
                    t.set_fontname(prefs['font'])
                    t.set_size(label_text_size)

                if ylabel:
                    t = ax.set_ylabel(ylabel)
                    t.set_family(prefs['font_family'])
                    t.set_fontname(prefs['font'])
                    t.set_size(label_text_size)
            else:
                self.ax.set_axis_off()

        # Create a plot title, if necessary
        if plot_title:
            self.ax.title = self.ax.text(
                0.5,
                1. + float(plot_title_padding) / height,
                plot_title,
                verticalalignment='bottom',
                horizontalalignment='center',
                size=pixelToPoint(plot_title_size, dpi),
                family=prefs['font_family'],
                fontname=prefs['font'])
            self.ax.title.set_transform(self.ax.transAxes)
            self.ax.title.set_family(prefs['font_family'])
            self.ax.title.set_fontname(prefs['font'])
        if stats_line:
            self.ax.stats = self.ax.text(0.5, (-stats_line_space) / height,
                                         stats_line,
                                         verticalalignment='top',
                                         horizontalalignment='center',
                                         size=pixelToPoint(
                                             stats_line_size, dpi))

            self.ax.stats.set_transform(self.ax.transAxes)
예제 #13
0
class QualityMapGraph(PlotBase):
    """
  The BarGraph class is a straightforward bar graph; given a dictionary
  of values, it takes the keys as the independent variable and the values
  as the dependent variable.
  """
    def __init__(self, data, ax, prefs, *args, **kw):

        PlotBase.__init__(self, data, ax, prefs, *args, **kw)
        if type(data) == types.DictType:
            self.gdata = GraphData(data)
        elif type(data) == types.InstanceType and data.__class__ == GraphData:
            self.gdata = data
        if self.prefs.has_key('span'):
            self.width = self.prefs['span']
        else:
            self.width = 1.0
            if self.gdata.key_type == "time":
                nKeys = self.gdata.getNumberOfKeys()
                self.width = (max(self.gdata.all_keys) -
                              min(self.gdata.all_keys)) / nKeys

        # Setup the colormapper to get the right colors
        self.cmap = LinearSegmentedColormap('quality_colormap', cdict, 256)
        #self.cmap = cm.RdYlGn
        self.norms = normalize(0, 100)
        mapper = cm.ScalarMappable(cmap=self.cmap, norm=self.norms)
        mapper = cm.ScalarMappable(cmap=cm.RdYlGn, norm=self.norms)

        def get_alpha(*args, **kw):
            return 1.0

        mapper.get_alpha = get_alpha
        self.mapper = mapper

    def draw(self):

        PlotBase.draw(self)
        self.x_formatter_cb(self.ax)

        if self.gdata.isEmpty():
            return None

        tmp_x = []
        tmp_y = []

        # Evaluate the bar width
        width = float(self.width)
        offset = 0.
        if self.gdata.key_type == 'time':
            width = width / 86400.0

        start_plot = 0
        end_plot = 0
        if "starttime" in self.prefs and "endtime" in self.prefs:
            start_plot = date2num(
                datetime.datetime.fromtimestamp(
                    to_timestamp(self.prefs['starttime'])))
            end_plot = date2num(
                datetime.datetime.fromtimestamp(
                    to_timestamp(self.prefs['endtime'])))

        labels = self.gdata.getLabels()
        nKeys = self.gdata.getNumberOfKeys()
        tmp_b = []
        tmp_x = []
        tmp_y = []

        self.bars = []
        labels = self.gdata.getLabels()
        nLabel = 0
        labelNames = []
        colors = []
        xmin = None
        xmax = None
        for label, num in labels:
            labelNames.append(label)
            for key, value in self.gdata.getPlotNumData(label):

                if xmin is None or xmin > (key + offset):
                    xmin = key + offset
                if xmax is None or xmax < (key + offset):
                    xmax = key + offset

                if value is not None:
                    colors.append(self.getQualityColor(value))
                    tmp_x.append(key + offset)
                    tmp_y.append(1.)
                    tmp_b.append(float(nLabel))

            nLabel += 1

        self.bars += self.ax.bar(tmp_x,
                                 tmp_y,
                                 bottom=tmp_b,
                                 width=width,
                                 color=colors)

        dpi = self.prefs.get('dpi', 100)
        setp(self.bars, linewidth=pixelToPoint(0.5, dpi), edgecolor='#AAAAAA')

        #pivots = keys
        #for idx in range(len(pivots)):
        #    self.coords[ pivots[idx] ] = self.bars[idx]

        ymax = float(nLabel)
        self.ax.set_xlim(xmin=0., xmax=xmax + width + offset)
        self.ax.set_ylim(ymin=0., ymax=ymax)
        if self.gdata.key_type == 'time':
            if start_plot and end_plot:
                self.ax.set_xlim(xmin=start_plot, xmax=end_plot)
            else:
                self.ax.set_xlim(xmin=min(tmp_x), xmax=max(tmp_x))
        self.ax.set_yticks([i + 0.5 for i in range(nLabel)])
        self.ax.set_yticklabels(labelNames)
        setp(self.ax.get_xticklines(), markersize=0.)
        setp(self.ax.get_yticklines(), markersize=0.)

        cax, kw = make_axes(self.ax, orientation='vertical', fraction=0.07)
        cb = ColorbarBase(cax, cmap=cm.RdYlGn, norm=self.norms)
        cb.draw_all()
        #cb = self.ax.colorbar( self.mapper, format="%d%%",
        #  orientation='horizontal', fraction=0.04, pad=0.1, aspect=40  )
        #setp( cb.outline, linewidth=.5 )
        #setp( cb.ax.get_xticklabels(), size=10 )
        #setp( cb.ax.get_xticklabels(), family=self.prefs['font_family'] )
        #setp( cb.ax.get_xticklabels(), fontname = self.prefs['font'] )

    def getQualityColor(self, value):

        if value is None or value < 0.:
            return "#FFFFFF"
        return self.mapper.to_rgba(value)

    def getLegendData(self):

        return None

    def x_formatter_cb(self, ax):
        if self.gdata.key_type == "string":
            smap = self.gdata.getStringMap()
            reverse_smap = {}
            for key, val in smap.items():
                reverse_smap[val] = key
            ticks = smap.values()
            ticks.sort()
            ax.set_xticks([i + .5 for i in ticks])
            ax.set_xticklabels([reverse_smap[i] for i in ticks])
            labels = ax.get_xticklabels()
            ax.grid(False)
            if self.log_xaxis:
                xmin = 0.001
            else:
                xmin = 0
            ax.set_xlim(xmin=xmin, xmax=len(ticks))
        elif self.gdata.key_type == "time":

            #ax.set_xlim( xmin=self.begin_num,xmax=self.end_num )
            dl = PrettyDateLocator()
            df = PrettyDateFormatter(dl)
            ax.xaxis.set_major_locator(dl)
            ax.xaxis.set_major_formatter(df)
            ax.xaxis.set_clip_on(False)
            sf = PrettyScalarFormatter()
            ax.yaxis.set_major_formatter(sf)
            #labels = ax.get_xticklabels()

        else:
            try:
                super(BarGraph, self).x_formatter_cb(ax)
            except:
                return None
예제 #14
0
파일: Graph.py 프로젝트: DIRACGrid/DIRAC
    def makeGraph(self, data, *args, **kw):

        start = time.time()

        # Evaluate all the preferences
        self.prefs = evalPrefs(*args, **kw)
        prefs = self.prefs

        if DEBUG:
            print("makeGraph time 1", time.time() - start)
            start = time.time()

        if "text_image" in prefs:
            self.makeTextGraph(str(prefs["text_image"]))
            return

        # Evaluate the number of plots and their requested layout
        metadata = prefs.get("metadata", {})
        plot_grid = prefs.get("plot_grid", "1:1")
        nx = int(plot_grid.split(":")[0])
        ny = int(plot_grid.split(":")[1])
        nPlots = nx * ny
        if nPlots == 1:
            if not isinstance(data, list):
                data = [data]
            if not isinstance(metadata, list):
                metadata = [metadata]
        else:
            if not isinstance(data, list):
                # return S_ERROR('Single data for multiplot graph')
                print("Single data for multiplot graph")
                return
            if not isinstance(metadata, list):
                metaList = []
                for _ in range(nPlots):
                    metaList.append(metadata)
                metadata = metaList

        # Initialize plot data
        graphData = []
        plot_prefs = []
        for i in range(nPlots):
            plot_prefs.append(evalPrefs(prefs, metadata[i]))
            gdata = GraphData(data[i])
            if i == 0:
                plot_type = plot_prefs[i]["plot_type"]
            if "sort_labels" in plot_prefs[i]:
                reverse = plot_prefs[i].get("reverse_labels", False)
                gdata.sortLabels(plot_prefs[i]["sort_labels"],
                                 reverse_order=reverse)
            if "limit_labels" in plot_prefs[i]:
                if plot_prefs[i]["limit_labels"] > 0:
                    gdata.truncateLabels(plot_prefs[i]["limit_labels"])
            if "cumulate_data" in plot_prefs[i]:
                gdata.makeCumulativeGraph()
            plot_title = plot_prefs[i].get("plot_title", "")
            if plot_title != "NoTitle":
                begin = ""
                end = ""
                if "starttime" in plot_prefs[i] and "endtime" in plot_prefs[i]:
                    begin = to_timestamp(plot_prefs[i]["starttime"])
                    end = to_timestamp(plot_prefs[i]["endtime"])
                elif gdata.key_type == "time":
                    begin = gdata.min_key
                    end = gdata.max_key
                if begin and end:
                    time_title = add_time_to_title(begin, end)
                    if plot_title:
                        plot_title += ":"
                    plot_prefs[i]["plot_title"] = plot_title + " " + time_title
            graphData.append(gdata)

        # Do not make legend for the plot with non-string keys (except for PieGraphs)
        if not graphData[0].subplots and graphData[
                0].key_type != "string" and not plot_type == "PieGraph":
            prefs["legend"] = False
        if prefs["legend"] and graphData[
                0].key_type != "string" and plot_type == "PieGraph":
            graphData[0].initialize(key_type="string")

        legend = Legend(graphData[0], None, prefs)
        self.figure = Figure()

        # Make Water Mark
        image = prefs.get("watermark", None)
        self.drawWaterMark(image)

        legend_ax, plot_axes = self.layoutFigure(legend)

        if DEBUG:
            print("makeGraph time layout", time.time() - start)
            start = time.time()

        # Make plots
        for i in range(nPlots):
            plot_type = plot_prefs[i]["plot_type"]
            try:
                # TODO: Remove when we moved to python3
                exec("import %s" % plot_type)
            except ImportError:
                print("Trying to use python like import")
                try:
                    exec("from . import  %s" % plot_type)
                except ImportError as x:
                    print("Failed to import graph type %s: %s" %
                          (plot_type, str(x)))
                    return None

            ax = plot_axes[i]
            plot = eval("%s.%s(graphData[i],ax,plot_prefs[i])" %
                        (plot_type, plot_type))
            plot.draw()

        if DEBUG:
            print("makeGraph time plots", time.time() - start)
            start = time.time()

        # Make legend
        if legend_ax:
            legend.setAxes(legend_ax)
            legend.draw()

        if DEBUG:
            print("makeGraph time legend", time.time() - start)
            start = time.time()
예제 #15
0
class QualityMapGraph( PlotBase ):

  """
  The BarGraph class is a straightforward bar graph; given a dictionary
  of values, it takes the keys as the independent variable and the values
  as the dependent variable.
  """

  def __init__( self, data, ax, prefs, *args, **kw ):

    PlotBase.__init__( self, data, ax, prefs, *args, **kw )
    if type( data ) == types.DictType:
      self.gdata = GraphData( data )
    elif type( data ) == types.InstanceType and data.__class__ == GraphData:
      self.gdata = data
    if self.prefs.has_key( 'span' ):
      self.width = self.prefs['span']
    else:
      self.width = 1.0
      if self.gdata.key_type == "time":
        nKeys = self.gdata.getNumberOfKeys()
        self.width = ( max( self.gdata.all_keys ) - min( self.gdata.all_keys ) ) / nKeys

    # Setup the colormapper to get the right colors
    self.cmap = LinearSegmentedColormap( 'quality_colormap', cdict, 256 )
    #self.cmap = cm.RdYlGn
    self.norms = normalize( 0, 100 )
    mapper = cm.ScalarMappable( cmap = self.cmap, norm = self.norms )
    mapper = cm.ScalarMappable( cmap = cm.RdYlGn, norm = self.norms )
    def get_alpha( *args, **kw ):
      return 1.0
    mapper.get_alpha = get_alpha
    self.mapper = mapper

  def draw( self ):

    PlotBase.draw( self )
    self.x_formatter_cb( self.ax )

    if self.gdata.isEmpty():
      return None

    tmp_x = []; tmp_y = []

    # Evaluate the bar width
    width = float( self.width )
    offset = 0.
    if self.gdata.key_type == 'time':
      width = width / 86400.0

    start_plot = 0
    end_plot = 0
    if "starttime" in self.prefs and "endtime" in self.prefs:
      start_plot = date2num( datetime.datetime.fromtimestamp( to_timestamp( self.prefs['starttime'] ) ) )
      end_plot = date2num( datetime.datetime.fromtimestamp( to_timestamp( self.prefs['endtime'] ) ) )

    labels = self.gdata.getLabels()
    nKeys = self.gdata.getNumberOfKeys()
    tmp_b = []
    tmp_x = []
    tmp_y = []

    self.bars = []
    labels = self.gdata.getLabels()
    nLabel = 0
    labelNames = []
    colors = []
    xmin = None
    xmax = None
    for label, num in labels:
      labelNames.append( label )
      for key, value in self.gdata.getPlotNumData( label ):

        if xmin is None or xmin > ( key + offset ):
          xmin = key + offset
        if xmax is None or xmax < ( key + offset ):
          xmax = key + offset

        if value is not None:
          colors.append( self.getQualityColor( value ) )
          tmp_x.append( key + offset )
          tmp_y.append( 1. )
          tmp_b.append( float( nLabel ) )

      nLabel += 1

    self.bars += self.ax.bar( tmp_x, tmp_y, bottom = tmp_b, width = width, color = colors )

    dpi = self.prefs.get( 'dpi', 100 )
    setp( self.bars, linewidth = pixelToPoint( 0.5, dpi ), edgecolor = '#AAAAAA' )

    #pivots = keys
    #for idx in range(len(pivots)):
    #    self.coords[ pivots[idx] ] = self.bars[idx]

    ymax = float( nLabel )
    self.ax.set_xlim( xmin = 0., xmax = xmax + width + offset )
    self.ax.set_ylim( ymin = 0., ymax = ymax )
    if self.gdata.key_type == 'time':
      if start_plot and end_plot:
        self.ax.set_xlim( xmin = start_plot, xmax = end_plot )
      else:
        self.ax.set_xlim( xmin = min( tmp_x ), xmax = max( tmp_x ) )
    self.ax.set_yticks( [ i + 0.5 for i in range( nLabel ) ] )
    self.ax.set_yticklabels( labelNames )
    setp( self.ax.get_xticklines(), markersize = 0. )
    setp( self.ax.get_yticklines(), markersize = 0. )

    cax, kw = make_axes( self.ax, orientation = 'vertical', fraction = 0.07 )
    cb = ColorbarBase( cax, cmap = cm.RdYlGn, norm = self.norms )
    cb.draw_all()
    #cb = self.ax.colorbar( self.mapper, format="%d%%", 
    #  orientation='horizontal', fraction=0.04, pad=0.1, aspect=40  )
    #setp( cb.outline, linewidth=.5 )
    #setp( cb.ax.get_xticklabels(), size=10 )
    #setp( cb.ax.get_xticklabels(), family=self.prefs['font_family'] )
    #setp( cb.ax.get_xticklabels(), fontname = self.prefs['font'] )

  def getQualityColor( self, value ):

    if value is None or value < 0.:
      return "#FFFFFF"
    return self.mapper.to_rgba( value )

  def getLegendData( self ):

    return None

  def x_formatter_cb( self, ax ):
    if self.gdata.key_type == "string":
      smap = self.gdata.getStringMap()
      reverse_smap = {}
      for key, val in smap.items():
        reverse_smap[val] = key
      ticks = smap.values()
      ticks.sort()
      ax.set_xticks( [i + .5 for i in ticks] )
      ax.set_xticklabels( [reverse_smap[i] for i in ticks] )
      labels = ax.get_xticklabels()
      ax.grid( False )
      if self.log_xaxis:
        xmin = 0.001
      else:
        xmin = 0
      ax.set_xlim( xmin = xmin, xmax = len( ticks ) )
    elif self.gdata.key_type == "time":

      #ax.set_xlim( xmin=self.begin_num,xmax=self.end_num )
      dl = PrettyDateLocator()
      df = PrettyDateFormatter( dl )
      ax.xaxis.set_major_locator( dl )
      ax.xaxis.set_major_formatter( df )
      ax.xaxis.set_clip_on( False )
      sf = PrettyScalarFormatter()
      ax.yaxis.set_major_formatter( sf )
      #labels = ax.get_xticklabels()

    else:
      try:
        super( BarGraph, self ).x_formatter_cb( ax )
      except:
        return None
예제 #16
0
    def makeGraph(self, data, *args, **kw):

        start = time.time()

        # Evaluate all the preferences
        self.prefs = evalPrefs(*args, **kw)
        prefs = self.prefs

        if DEBUG:
            print "makeGraph time 1", time.time() - start
            start = time.time()

        if prefs.has_key('text_image'):
            self.makeTextGraph(str(prefs['text_image']))
            return

        # Evaluate the number of plots and their requested layout
        metadata = prefs.get('metadata', {})
        plot_grid = prefs.get('plot_grid', '1:1')
        nx = int(plot_grid.split(':')[0])
        ny = int(plot_grid.split(':')[1])
        nPlots = nx * ny
        if nPlots == 1:
            if not isinstance(data, list):
                data = [data]
            if not isinstance(metadata, list):
                metadata = [metadata]
        else:
            if not isinstance(data, list):
                #return S_ERROR('Single data for multiplot graph')
                print 'Single data for multiplot graph'
                return
            if not isinstance(metadata, list):
                metaList = []
                for _ in range(nPlots):
                    metaList.append(metadata)
                metadata = metaList

        # Initialize plot data
        graphData = []
        plot_prefs = []
        for i in range(nPlots):
            plot_prefs.append(evalPrefs(prefs, metadata[i]))
            gdata = GraphData(data[i])
            if i == 0: plot_type = plot_prefs[i]['plot_type']
            if plot_prefs[i].has_key('sort_labels'):
                reverse = plot_prefs[i].get('reverse_labels', False)
                gdata.sortLabels(plot_prefs[i]['sort_labels'],
                                 reverse_order=reverse)
            if plot_prefs[i].has_key('limit_labels'):
                if plot_prefs[i]['limit_labels'] > 0:
                    gdata.truncateLabels(plot_prefs[i]['limit_labels'])
            if plot_prefs[i].has_key('cumulate_data'):
                gdata.makeCumulativeGraph()
            plot_title = plot_prefs[i].get('plot_title', '')
            if plot_title != "NoTitle":
                begin = ''
                end = ''
                if plot_prefs[i].has_key(
                        'starttime') and plot_prefs[i].has_key('endtime'):
                    begin = to_timestamp(plot_prefs[i]['starttime'])
                    end = to_timestamp(plot_prefs[i]['endtime'])
                elif gdata.key_type == "time":
                    begin = gdata.min_key
                    end = gdata.max_key
                if begin and end:
                    time_title = add_time_to_title(begin, end)
                    if plot_title:
                        plot_title += ":"
                    plot_prefs[i]['plot_title'] = plot_title + ' ' + time_title
            graphData.append(gdata)

        # Do not make legend for the plot with non-string keys (except for PieGraphs)
        if not graphData[0].subplots and graphData[
                0].key_type != 'string' and not plot_type == 'PieGraph':
            prefs['legend'] = False
        if prefs['legend'] and graphData[
                0].key_type != 'string' and plot_type == 'PieGraph':
            graphData[0].initialize(key_type='string')

        legend = Legend(graphData[0], None, prefs)
        self.figure = Figure()

        # Make Water Mark
        image = prefs.get('watermark', None)
        self.drawWaterMark(image)

        legend_ax, plot_axes = self.layoutFigure(legend)

        if DEBUG:
            print "makeGraph time layout", time.time() - start
            start = time.time()

        # Make plots
        for i in range(nPlots):
            plot_type = plot_prefs[i]['plot_type']
            try:
                exec "import %s" % plot_type
            except ImportError, x:
                print "Failed to import graph type %s: %s" % (plot_type,
                                                              str(x))
                return None

            ax = plot_axes[i]
            plot = eval("%s.%s(graphData[i],ax,plot_prefs[i])" %
                        (plot_type, plot_type))
            plot.draw()
예제 #17
0
파일: Graph.py 프로젝트: DIRACGrid/DIRAC
  def makeGraph(self, data, *args, **kw):

    start = time.time()

    # Evaluate all the preferences
    self.prefs = evalPrefs(*args,**kw)
    prefs = self.prefs

    if DEBUG:
      print "makeGraph time 1",time.time()-start
      start = time.time()

    if prefs.has_key('text_image'):
      self.makeTextGraph(str(prefs['text_image']))
      return

    # Evaluate the number of plots and their requested layout
    metadata = prefs.get('metadata',{})
    plot_grid = prefs.get('plot_grid','1:1')
    nx = int(plot_grid.split(':')[0])
    ny = int(plot_grid.split(':')[1])
    nPlots = nx*ny
    if nPlots == 1:
      if not isinstance( data, list ):
        data = [data]
      if not isinstance(metadata, list):
        metadata = [metadata]
    else:
      if not isinstance( data, list ):
        #return S_ERROR('Single data for multiplot graph')
        print 'Single data for multiplot graph'
        return
      if not isinstance(metadata, list):
        metaList = []
        for _ in range( nPlots ):
          metaList.append(metadata)
        metadata = metaList

    # Initialize plot data
    graphData = []
    plot_prefs = []
    for i in range(nPlots):
      plot_prefs.append(evalPrefs(prefs,metadata[i]))
      gdata = GraphData(data[i])
      if i == 0: plot_type = plot_prefs[i]['plot_type']
      if plot_prefs[i].has_key('sort_labels'):
        reverse = plot_prefs[i].get( 'reverse_labels', False )
        gdata.sortLabels(plot_prefs[i]['sort_labels'], reverse_order = reverse )
      if plot_prefs[i].has_key('limit_labels'):
        if plot_prefs[i]['limit_labels'] > 0:
          gdata.truncateLabels(plot_prefs[i]['limit_labels'])
      if plot_prefs[i].has_key('cumulate_data'):
        gdata.makeCumulativeGraph()
      plot_title = plot_prefs[i].get('plot_title','')
      if plot_title != "NoTitle":
        begin = ''
        end = ''
        if plot_prefs[i].has_key('starttime') and plot_prefs[i].has_key('endtime'):
          begin = to_timestamp(plot_prefs[i]['starttime'])
          end = to_timestamp(plot_prefs[i]['endtime'])
        elif gdata.key_type == "time" :
          begin = gdata.min_key
          end = gdata.max_key
        if begin and end:
          time_title = add_time_to_title(begin,end)
          if plot_title:
            plot_title += ":"
          plot_prefs[i]['plot_title'] = plot_title+' '+time_title
      graphData.append(gdata)

    # Do not make legend for the plot with non-string keys (except for PieGraphs)
    if not graphData[0].subplots and graphData[0].key_type != 'string' and not plot_type == 'PieGraph':
      prefs['legend'] = False
    if prefs['legend'] and graphData[0].key_type != 'string' and plot_type == 'PieGraph':
      graphData[0].initialize(key_type='string')

    legend = Legend(graphData[0],None,prefs)
    self.figure = Figure()

    # Make Water Mark
    image = prefs.get('watermark',None)
    self.drawWaterMark(image)

    legend_ax, plot_axes = self.layoutFigure(legend)

    if DEBUG:
      print "makeGraph time layout",time.time()-start
      start = time.time()

    # Make plots
    for i in range(nPlots):
      plot_type = plot_prefs[i]['plot_type']
      try:
        exec "import %s" % plot_type
      except ImportError, x:
        print "Failed to import graph type %s: %s" % ( plot_type, str( x ) )
        return None

      ax = plot_axes[i]
      plot = eval("%s.%s(graphData[i],ax,plot_prefs[i])" % (plot_type,plot_type) )
      plot.draw()
예제 #18
0
class PlotBase( object ):

  def __init__( self, data = None, axes = None, *aw, **kw ):

    self.ax_contain = axes
    self.canvas = None
    self.figure = None
    if self.ax_contain:
      self.figure = self.ax_contain.get_figure()
      self.canvas = self.figure.canvas
      self.dpi = self.ax_contain.figure.get_dpi()
      self.ax_contain.set_axis_off()
    self.prefs = evalPrefs( *aw, **kw )
    self.coords = {}
    self.palette = Palette()
    if isinstance( data, dict):
      self.gdata = GraphData( data )
    elif isinstance( data, object) and data.__class__ == GraphData:
      self.gdata = data

  def dumpPrefs( self ):

    for key in self.prefs:
      print key.rjust( 20 ), ':', str( self.prefs[key] ).ljust( 40 )

  def setAxes( self, axes ):

    self.ax_contain = axes
    self.ax_contain.set_axis_off()
    self.figure = self.ax_contain.get_figure()
    self.canvas = self.figure.canvas
    self.dpi = self.ax_contain.figure.get_dpi()

  def draw( self ):

    prefs = self.prefs
    dpi = self.ax_contain.figure.get_dpi()

    # Update palette
    palette = prefs.get( 'colors', {} )
    if palette:
      self.palette.addPalette( palette )


    xlabel = prefs.get( 'xlabel', '' )
    ylabel = prefs.get( 'ylabel', '' )
    xticks_flag = prefs.get( 'xticks', True )
    yticks_flag = prefs.get( 'yticks', True )

    text_size = prefs['text_size']
    text_padding = prefs['text_padding']

    label_text_size = prefs.get( 'label_text_size', text_size )
    label_text_size_point = pixelToPoint( label_text_size, dpi )
    tick_text_size = prefs.get( 'tick_text_size', text_size )
    tick_text_size_point = pixelToPoint( tick_text_size, dpi )

    ytick_length = prefs.get( 'ytick_length', 7 * tick_text_size )

    plot_title = prefs.get( 'plot_title', '' )
    if not plot_title or plot_title == 'NoTitle':
      plot_title_size = 0
      plot_title_padding = 0
    else:
      plot_title_size = prefs.get( 'plot_title_size', text_size )
      plot_title_padding = prefs.get( 'plot_text_padding', text_padding )
    plot_title_size_point = pixelToPoint( plot_title_size, dpi )

    stats_flag = prefs.get( 'statistics_line', False )
    stats_line = ''
    stats_line_space = 0.
    if stats_flag:
      stats_line = self.gdata.getStatString()
      stats_line_size = label_text_size
      stats_line_padding = label_text_size * 2.
      stats_line_space = stats_line_size + stats_line_padding

    plot_padding = prefs['plot_padding']
    plot_left_padding = prefs.get( 'plot_left_padding', plot_padding )
    plot_right_padding = prefs.get( 'plot_right_padding', 0 )
    plot_bottom_padding = prefs.get( 'plot_bottom_padding', plot_padding )
    plot_top_padding = prefs.get( 'plot_top_padding', 0 )
    frame_flag = prefs['frame']

    # Create plot axes, and set properties
    left, bottom, width, height = self.ax_contain.get_window_extent().bounds
    l, b, f_width, f_height = self.figure.get_window_extent().bounds

    # Space needed for labels and ticks
    x_label_space = 0
    if xticks_flag:
      x_label_space += tick_text_size * 1.5
    if xlabel:
      x_label_space += label_text_size * 1.5
    y_label_space = 0
    if yticks_flag:
      y_label_space += ytick_length
    if ylabel:
      y_label_space += label_text_size * 1.5

    ax_plot_rect = ( float( plot_left_padding + left + y_label_space ) / f_width,
                     float( plot_bottom_padding + bottom + x_label_space + stats_line_space ) / f_height,
                     float( width - plot_left_padding - plot_right_padding - y_label_space ) / f_width,
                     float( height - plot_bottom_padding - plot_top_padding - x_label_space - \
                            plot_title_size - 2 * plot_title_padding - stats_line_space ) / f_height )
    ax = Axes( self.figure, ax_plot_rect )
    if prefs['square_axis']:
      l, b, a_width, a_height = ax.get_window_extent().bounds
      delta = abs( a_height - a_width )
      if a_height > a_width:
        a_height = a_width
        ax_plot_rect = ( float( plot_left_padding + left ) / f_width,
                         float( plot_bottom_padding + bottom + delta / 2. ) / f_height,
                         float( width - plot_left_padding - plot_right_padding ) / f_width,
                         float( height - plot_bottom_padding - plot_title_size - 2 * plot_title_padding - delta ) / f_height )
      else:
        a_width = a_height
        ax_plot_rect = ( float( plot_left_padding + left + delta / 2. ) / f_width,
                         float( plot_bottom_padding + bottom ) / f_height,
                         float( width - plot_left_padding - delta ) / f_width,
                         float( height - plot_bottom_padding - plot_title_size - 2 * plot_title_padding ) / f_height )
      ax.set_position( ax_plot_rect )


    self.figure.add_axes( ax )
    self.ax = ax
    frame = ax.patch
    frame.set_fill( False )

    if frame_flag.lower() == 'off':
      self.ax.set_axis_off()
      self.log_xaxis = False
      self.log_yaxis = False
    else:
      # If requested, make x/y axis logarithmic
      if prefs.get( 'log_xaxis', 'False' ).find( 'r' ) >= 0:
        ax.semilogx()
        self.log_xaxis = True
      else:
        self.log_xaxis = False
      if prefs.get( 'log_yaxis', 'False' ).find( 'r' ) >= 0:
        ax.semilogy()
        self.log_yaxis = True
      else:
        self.log_yaxis = False

      if xticks_flag:
        setp( ax.get_xticklabels(), family = prefs['font_family'] )
        setp( ax.get_xticklabels(), fontname = prefs['font'] )
        setp( ax.get_xticklabels(), size = tick_text_size_point )
      else:
        setp( ax.get_xticklabels(), size = 0 )

      if yticks_flag:
        setp( ax.get_yticklabels(), family = prefs['font_family'] )
        setp( ax.get_yticklabels(), fontname = prefs['font'] )
        setp( ax.get_yticklabels(), size = tick_text_size_point )
      else:
        setp( ax.get_yticklabels(), size = 0 )

      setp( ax.get_xticklines(), markeredgewidth = pixelToPoint( 0.5, dpi ) )
      setp( ax.get_xticklines(), markersize = pixelToPoint( text_size / 2., dpi ) )
      setp( ax.get_yticklines(), markeredgewidth = pixelToPoint( 0.5, dpi ) )
      setp( ax.get_yticklines(), markersize = pixelToPoint( text_size / 2., dpi ) )
      setp( ax.get_xticklines(), zorder = 4.0 )

      line_width = prefs.get( 'line_width', 1.0 )
      frame_line_width = prefs.get( 'frame_line_width', line_width )
      grid_line_width = prefs.get( 'grid_line_width', 0.1 )
      plot_line_width = prefs.get( 'plot_line_width', 0.1 )

      setp( ax.patch, linewidth = pixelToPoint( plot_line_width, dpi ) )
      #setp( ax.spines, linewidth=pixelToPoint(frame_line_width,dpi) )
      #setp( ax.axvline(), linewidth=pixelToPoint(1.0,dpi) )
      axis_grid_flag = prefs.get( 'plot_axis_grid', True )
      if axis_grid_flag:
        ax.grid( True, color = '#555555', linewidth = pixelToPoint( grid_line_width, dpi ) )

      plot_axis_flag = prefs.get( 'plot_axis', True )
      if plot_axis_flag:
      # Set labels
        if xlabel:
          t = ax.set_xlabel( xlabel )
          t.set_family( prefs['font_family'] )
          t.set_fontname( prefs['font'] )
          t.set_size( label_text_size )

        if ylabel:
          t = ax.set_ylabel( ylabel )
          t.set_family( prefs['font_family'] )
          t.set_fontname( prefs['font'] )
          t.set_size( label_text_size )
      else:
        self.ax.set_axis_off()


    # Create a plot title, if necessary
    if plot_title:
      self.ax.title = self.ax.text( 0.5,
                                    1. + float( plot_title_padding ) / height,
                                    plot_title,
                                    verticalalignment = 'bottom',
                                    horizontalalignment = 'center',
                                    size = pixelToPoint( plot_title_size, dpi ),
                                    family = prefs['font_family'],
                                    fontname = prefs['font'])
      self.ax.title.set_transform( self.ax.transAxes )
      self.ax.title.set_family( prefs['font_family'] )
      self.ax.title.set_fontname( prefs['font'] )
    if stats_line:
      self.ax.stats = self.ax.text( 0.5, ( -stats_line_space ) / height,
                                    stats_line,
                                    verticalalignment = 'top',
                                    horizontalalignment = 'center',
                                    size = pixelToPoint( stats_line_size, dpi ) )

      self.ax.stats.set_transform( self.ax.transAxes )