コード例 #1
0
    def testRefineWithRanges(self):
        #Test refining rule with ranges (refs #10815)

        #First, try with a field based category (id)
        ranges = []
        ranges.append(QgsRendererRangeV2(0, 1, QgsMarkerSymbolV2(), "0-1"))
        ranges.append(QgsRendererRangeV2(1, 2, QgsMarkerSymbolV2(), "1-2"))
        g = QgsGraduatedSymbolRendererV2("id", ranges)

        QgsRuleBasedRendererV2.refineRuleRanges(self.r2, g)
        assert self.r2.children()[0].filterExpression() == '"id" >= 0.0000 AND "id" <= 1.0000'
        assert self.r2.children()[1].filterExpression() == '"id" > 1.0000 AND "id" <= 2.0000'

        #Next try with an expression based range
        ranges = []
        ranges.append(QgsRendererRangeV2(0, 1, QgsMarkerSymbolV2(), "0-1"))
        ranges.append(QgsRendererRangeV2(1, 2, QgsMarkerSymbolV2(), "1-2"))
        g = QgsGraduatedSymbolRendererV2("id / 2", ranges)

        QgsRuleBasedRendererV2.refineRuleRanges(self.r1, g)
        assert self.r1.children()[0].filterExpression() == '(id / 2) >= 0.0000 AND (id / 2) <= 1.0000'
        assert self.r1.children()[1].filterExpression() == '(id / 2) > 1.0000 AND (id / 2) <= 2.0000'

        #Last try with an expression which is just a quoted field name
        ranges = []
        ranges.append(QgsRendererRangeV2(0, 1, QgsMarkerSymbolV2(), "0-1"))
        ranges.append(QgsRendererRangeV2(1, 2, QgsMarkerSymbolV2(), "1-2"))
        g = QgsGraduatedSymbolRendererV2('"id"', ranges)

        QgsRuleBasedRendererV2.refineRuleRanges(self.r3, g)
        assert self.r3.children()[0].filterExpression() == '"id" >= 0.0000 AND "id" <= 1.0000'
        assert self.r3.children()[1].filterExpression() == '"id" > 1.0000 AND "id" <= 2.0000'
コード例 #2
0
    def testConvertFromGraduatedRenderer(self):
        # Test converting graduated renderer to rule based

        # First, try with a field based category (id)
        ranges = []
        ranges.append(QgsRendererRangeV2(0, 1, QgsMarkerSymbolV2(), "0-1"))
        ranges.append(QgsRendererRangeV2(1, 2, QgsMarkerSymbolV2(), "1-2"))
        g = QgsGraduatedSymbolRendererV2("id", ranges)

        r = QgsRuleBasedRendererV2.convertFromRenderer(g)
        self.assertEqual(r.rootRule().children()[0].filterExpression(), '"id" >= 0.000000 AND "id" <= 1.000000')
        self.assertEqual(r.rootRule().children()[1].filterExpression(), '"id" > 1.000000 AND "id" <= 2.000000')

        # Next try with an expression based range
        ranges = []
        ranges.append(QgsRendererRangeV2(0, 1, QgsMarkerSymbolV2(), "0-1"))
        ranges.append(QgsRendererRangeV2(1, 2, QgsMarkerSymbolV2(), "1-2"))
        g = QgsGraduatedSymbolRendererV2("id / 2", ranges)

        r = QgsRuleBasedRendererV2.convertFromRenderer(g)
        self.assertEqual(r.rootRule().children()[0].filterExpression(), '(id / 2) >= 0.000000 AND (id / 2) <= 1.000000')
        self.assertEqual(r.rootRule().children()[1].filterExpression(), '(id / 2) > 1.000000 AND (id / 2) <= 2.000000')

        # Last try with an expression which is just a quoted field name
        ranges = []
        ranges.append(QgsRendererRangeV2(0, 1, QgsMarkerSymbolV2(), "0-1"))
        ranges.append(QgsRendererRangeV2(1, 2, QgsMarkerSymbolV2(), "1-2"))
        g = QgsGraduatedSymbolRendererV2('"id"', ranges)

        r = QgsRuleBasedRendererV2.convertFromRenderer(g)
        self.assertEqual(r.rootRule().children()[0].filterExpression(), '"id" >= 0.000000 AND "id" <= 1.000000')
        self.assertEqual(r.rootRule().children()[1].filterExpression(), '"id" > 1.000000 AND "id" <= 2.000000')
コード例 #3
0
    def __getGraduatedSymbolRenderer(self):
        """docstring for __getGraduatedSymbolRenderer"""

        #Comprobar que los atributos sean el mismo, sino renderizar por basado en reglas
        if len(set(self.attributes)) != 1:
            return self.__getRuleBasedRenderer()

        rangelist = []
        field = self.has_classitem if self.has_classitem == self.attributes[
            0] else self.attributes[0]

        for exp, msclass in zip(self.expressions[::-1],
                                self.mslayer["classes"][::-1]):
            Symbol = SymbolImport(msclass, self.qgslayer, self.geom_type, self.sizeunits, \
                self.mssymbols, self.symbolsetpath, self.fontset)
            symbol = Symbol.getSymbol()
            label = msclass.get("name", exp[1])
            render = False if msclass.get("status",
                                          'on').lower() == 'off' else True
            rangelist.append(
                QgsRendererRangeV2(exp[3], exp[4], symbol, label, render))

        renderer = QgsGraduatedSymbolRendererV2(field, rangelist)
        renderer.setMode(QgsGraduatedSymbolRendererV2.Custom)
        return renderer
コード例 #4
0
    def createChoropleth(self, layer, min, max, num_classes=10):

        myTargetField = HASC().valueField
        myRangeList = []
        myOpacity = 1

        step = (max - min) / num_classes
        col_step = 256 / (num_classes - 1)

        for i in range(num_classes):
            label = str(min + step * i) + " - " + str(min + step * (i + 1))
            hex_level = hex(int(col_step * i)).split('x')[1]
            if (len(hex_level) < 2):
                hex_level = "0" + hex_level
            colour = "#" + hex_level + hex_level + hex_level
            symbol = QgsFillSymbolV2.createSimple({
                'color': colour,
                'color_border': colour,
                'width_border': '0'
            })
            symbol.setAlpha(myOpacity)
            myRangeList.append(
                QgsRendererRangeV2(min + step * i, min + step * (i + 1),
                                   symbol, label))

        renderer = QgsGraduatedSymbolRendererV2('', myRangeList)
        renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
        renderer.setClassAttribute(myTargetField)
        layer.setRendererV2(renderer)
コード例 #5
0
    def symbolize(self):
        # define ranges: label, lower value, upper value, color name
        temp_cat = (('0-10', 0.0, 10.0, '"#0024E3'), ('10-12', 10.0, 12.0,
                                                      '#0087CD'),
                    ('12-14', 12.0, 14.0,
                     '#16F45A'), ('14-16', 14.0, 16.0,
                                  '#73FF1A'), ('16-18', 16.0, 18.0, '#BDFF0C'),
                    ('18-20', 18.0, 20.0,
                     '#FFDD00'), ('20-22', 20.0, 22.0,
                                  '#FF9000'), ('22-24', 22.0, 24.0, '#FF4400'),
                    ('24-26', 24.0, 26.0,
                     '#FF1D00'), ('26-28', 26.0, 28.0,
                                  'F70000'), ('>28', 28.0, 40.0, '#AA0000'))

        # create a category for each item in Augmean
        ranges = []
        for label, lower, upper, color in temp_cat:
            symbol = QgsSymbolV2.defaultSymbol(self.layer.geometryType())
            symbol.setColor(QColor(color))
            symbol.setWidth(0.5)
            rng = QgsRendererRangeV2(lower, upper, symbol, label)
            ranges.append(rng)

        # create the renderer and assign it to a layer
        expression = []
        for feature in layer.getFeatures():
            attrs = feature.attributes()
            sum(attrs[29:33]) / 6
        self.renderer = QgsGraduatedSymbolRendererV2(expression, ranges)
コード例 #6
0
    def showLegend(self, layer, field, setting_list):
        if not self.cellstyle:
            self.styleManager = QgsMapLayerStyleManager(layer)
            self.styleManager.addStyleFromLayer(u'默认')
            self.cellstyle = True

        ranges = []
        flabel = QLabel(field)
        fl = QHBoxLayout()
        fl.addWidget(flabel)
        self.vbox.addLayout(fl)
        for bl in setting_list:
            widget = QWidget(self)
            widget.setStyleSheet('QWidget {background-color:%s}' %
                                 bl[0].name())
            widget.resize(20, 20)
            label = QLabel(str(bl[1]) + u'—' + str(bl[2]))
            c = QHBoxLayout()
            c.addWidget(widget)
            c.addWidget(label)
            c.setStretchFactor(widget, 1)
            c.setStretchFactor(label, 3)
            self.vbox.addLayout(c)

            sym = QgsSymbolV2.defaultSymbol(layer.geometryType())
            sym.setColor(bl[0])
            rng = QgsRendererRangeV2(bl[1], bl[2], sym, label.text())
            ranges.append(rng)

        self.vbox.addStretch(1)
        self.setLayout(self.vbox)

        renderer = QgsGraduatedSymbolRendererV2(field, ranges)
        layer.setRendererV2(renderer)
        self.iface.actionDraw().trigger()
 def create_join_renderer(self, layer, field, classes, mode, color='PuBu'):
     symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
     style = QgsStyleV2().defaultStyle()
     colorRamp = style.colorRampRef(color)
     renderer = QgsGraduatedSymbolRendererV2.createRenderer(layer, field, classes, mode, symbol, colorRamp)
     label_format = self.create_join_label_format(2)
     renderer.setLabelFormat(label_format)
     return renderer
コード例 #8
0
def create_join_renderer(layer, field, classes, mode, color='Blues'):
    symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    style = QgsStyleV2().defaultStyle()
    colorRamp = style.colorRampRef(color)
    renderer = QgsGraduatedSymbolRendererV2.createRenderer(
        layer, field, classes, mode, symbol, colorRamp)
    label_format = create_join_label_format(2)
    renderer.setLabelFormat(label_format)
    return renderer
コード例 #9
0
    def render_and_save_pointwise_output_layer(
            self,
            pointwise_output_csv_filepath,
            output_layer_name,
            on_values_of_attribute,
            graduated_rendering_interval_points,
            shapefile_path=''):

        uri = 'file:///' + pointwise_output_csv_filepath + \
         '?delimiter=%s&crs=epsg:32643&xField=%s&yField=%s' % (',', 'X', 'Y')
        output_layer = QgsVectorLayer(uri, output_layer_name, 'delimitedtext')

        if 'Crop' in on_values_of_attribute:
            ET_D_max = max([
                point.budget.PET_minus_AET_crop_end
                for point in model_calculator.output_grid_points
            ])
        elif 'Monsoon' in on_values_of_attribute:
            ET_D_max = max([
                point.budget.PET_minus_AET_monsoon_end
                for point in model_calculator.output_grid_points
            ])

        graduated_symbol_renderer_range_list = []
        opacity = 1
        intervals_count = len(graduated_rendering_interval_points)
        for i in range(intervals_count):
            interval_min = 0 if graduated_rendering_interval_points[
                i] == 0 else (
                    graduated_rendering_interval_points[i] * ET_D_max / 100.0 +
                    0.01)
            interval_max = (graduated_rendering_interval_points * ET_D_max /
                            100.0)
            label = "{0:.2f} - {1:.2f}".format(interval_min, interval_max)
            colour = QColor(
                int(255 * (1 - (i + 1.0) / (intervals_count + 1.0))), 0,
                0)  # +1 done to tackle boundary cases
            symbol = QgsSymbolV2.defaultSymbol(output_layer.geometryType())
            symbol.setColor(colour)
            symbol.setAlpha(opacity)
            interval_range = QgsRendererRangeV2(interval_min, interval_max,
                                                symbol, label)
            graduated_symbol_renderer_range_list.append(interval_range)
        renderer = QgsGraduatedSymbolRendererV2(
            '', graduated_symbol_renderer_range_list)
        renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
        renderer.setClassAttribute(on_values_of_attribute)
        output_layer.setRendererV2(renderer)
        QgsMapLayerRegistry.instance().addMapLayer(output_layer)

        if shapefile_path != '':
            QgsVectorFileWriter.writeAsVectorFormat(output_layer,
                                                    shapefile_path, "utf-8",
                                                    None, "ESRI Shapefile")

        return output_layer
コード例 #10
0
ファイル: symbology.py プロジェクト: aecforge/QEPANET
    def make_graduated_sym_renderer(self, layer, field_name, ranges_colors=None):

        feats = layer.getFeatures()

        min_val = sys.float_info.max
        max_val = -min_val

        # Find values range
        for feat in feats:
            attr = feat.attribute(field_name)
            val = float(attr)
            if val < min_val:
                min_val = val
            if val > max_val:
                max_val = val

        # Define colors
        if ranges_colors is None:
            ranges_colors = []
            colors = [
                QColor(0, 255, 0),
                QColor(128, 255, 0),
                QColor(255, 255, 0),
                QColor(255, 128, 0),
                QColor(255, 0, 0)]

            intv_nr = len(colors)
            intv = (max_val - min_val) / intv_nr
            for c in range(intv_nr):
                vrange = [min_val + intv * c, min_val + intv * (c + 1)]

                if c == len(colors) - 1:
                    vrange[1] = max_val

                ranges_colors.append([vrange, colors[c]])

        range_list = []
        for range_col in ranges_colors:
            r_min = range_col[0][0]
            r_max = range_col[0][1]
            title = str(r_min) + ' - ' + str(r_max)
            range_list.append(symbology_from_range(layer, r_min, r_max, range_col[1], title))

        renderer = QgsGraduatedSymbolRendererV2(field_name, range_list)

        # Line
        symbol = QgsMarkerSymbolV2().createSimple({})
        symbol.deleteSymbolLayer(0)
        mark_sym_lay = QgsSimpleMarkerSymbolLayerV2()
        symbol.appendSymbolLayer(mark_sym_lay)

        # renderer.setSourceSymbol(symbol)
        renderer.updateSymbols(symbol)

        return renderer
コード例 #11
0
def makeGraduatedRendererFromDivisionsList(layer, fieldName, divisions):
    classes = len(divisions) - 1
    rangeList = []
    for i in range(classes):
        label = str(divisions[i]) + " - " + str(divisions[i + 1])
        rangeList.append(
            makeSymbologyForRange(layer, divisions[i], divisions[i + 1], label,
                                  arbitaryColor(i, classes)))
    renderer = QgsGraduatedSymbolRendererV2(fieldName, rangeList)
    renderer.setMode(QgsGraduatedSymbolRendererV2.Custom)
    return renderer
コード例 #12
0
    def _apply_symbology_fixed_divisions(self, layer, field, tbl_name, schema,
                                         min_v, max_v, steps):
        """Finds the amount of levels that is necessary to describe the layer,
        a maximum of 20 different levels is set"""
        if min_v is not None and max_v is not None:
            distinct_values = list(np.arange(min_v, max_v, steps))
        else:
            distinct = self.DB.get_distinct(tbl_name, field, schema)
            distinct_values = []
            distinct_count = []
            for value, count in distinct:
                distinct_values.append(value)
                distinct_count.append(count)
            if len(distinct_values) > 20:
                distinct_values.sort()
                temp_list = []
                for val in range(0, len(distinct_values),
                                 int(round(len(distinct_values) / 20))):
                    temp_list.append(distinct_values[val])
                distinct_values = temp_list

        colors = self._create_colors(len(distinct_values))
        try:
            range_list = []
            for i in range(len(distinct_values) - 1):
                red, green, blue = colors[i]
                range_list.append(
                    self._make_symbology(
                        layer, distinct_values[i], distinct_values[i + 1],
                        str(distinct_values[i]) + ' - ' +
                        str(distinct_values[i + 1]),
                        QColor(int(red * 255), int(green * 255),
                               int(blue * 255), 128)))
            renderer = QgsGraduatedSymbolRendererV2(field, range_list)
            renderer.setMode(QgsGraduatedSymbolRendererV2.Custom)
        except TypeError:
            categories = []
            for i in range(len(distinct_values)):
                symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
                red, green, blue = colors[i]
                symbol.setColor(
                    QColor(int(red * 255), int(green * 255), int(blue * 255),
                           128))
                symbol.symbolLayer(0).setOutlineColor(
                    QColor(int(red * 255), int(green * 255), int(blue * 255),
                           128))
                category = QgsRendererCategoryV2(str(distinct_values[i]),
                                                 symbol,
                                                 str(distinct_values[i]))
                categories.append(category)
            renderer = QgsCategorizedSymbolRendererV2(field, categories)
            #renderer.setMode(QgsCategorizedSymbolRendererV2.Custom)
        layer.setRendererV2(renderer)
コード例 #13
0
 def prepare_renderer(levels, inter_time, lenpoly):
     cats = [('{} - {} min'.format(levels[i] - inter_time, levels[i]),
              levels[i] - inter_time, levels[i])
             for i in xrange(lenpoly)]  # label, lower bound, upper bound
     colors = get_isochrones_colors(len(levels))
     ranges = []
     for ix, cat in enumerate(cats):
         symbol = QgsFillSymbolV2()
         symbol.setColor(QtGui.QColor(colors[ix]))
         rng = QgsRendererRangeV2(cat[1], cat[2], symbol, cat[0])
         ranges.append(rng)
     expression = 'max'
     return QgsGraduatedSymbolRendererV2(expression, ranges)
コード例 #14
0
    def add_symbology(self):
        low_color = self.color_low_value.color()
        high_color = self.color_high_value.color()
        index = self.cbx_mode.currentIndex()
        mode = self.cbx_mode.itemData(index)
        classes = self.spinBox_classes.value()

        # Compute renderer
        # noinspection PyArgumentList
        symbol = QgsSymbolV2.defaultSymbol(QGis.Polygon)

        color_ramp = QgsVectorGradientColorRampV2(low_color, high_color)
        # noinspection PyArgumentList
        renderer = QgsGraduatedSymbolRendererV2.createRenderer(
            self.output_layer, self.name_field, classes, mode, symbol,
            color_ramp)
        self.output_layer.setRendererV2(renderer)
コード例 #15
0
    def testQgsGraduatedSymbolRendererV2_3(self):
        """Test QgsGraduatedSymbolRendererV2: Reading attribute data, calculating classes """

        # Create a renderer
        renderer = QgsGraduatedSymbolRendererV2()
        symbol = createMarkerSymbol()
        renderer.setSourceSymbol(symbol.clone())

        # Test retrieving data values from a layer
        ml = createMemoryLayer((1.2, 0.5, 5.0, 1.0, 1.0, 1.2))
        # ... by attribute
        renderer.setClassAttribute("value")
        self.assertEqual(renderer.classAttribute(), "value",
                         "Error in set/get classAttribute")
        data = renderer.getDataValues(ml)
        datastr = ':'.join([str(x) for x in data])
        self.assertEqual(datastr, '1.2:0.5:5.0:1.0:1.0:1.2',
                         "Error returning field data")
        # ... by expression
        renderer.setClassAttribute('"value"*"value"')
        self.assertEqual(renderer.classAttribute(), '"value"*"value"',
                         "Error in set/get classAttribute")
        data = renderer.getDataValues(ml)
        datastr = ':'.join([str(x) for x in data])
        self.assertEqual(datastr, '1.44:0.25:25.0:1.0:1.0:1.44',
                         "Error returning field expression")

        renderer.setClassAttribute("value")
        # Equal interval calculations
        renderer.updateClasses(ml, renderer.EqualInterval, 3)
        self.assertEqual(dumpRangeBreaks(renderer.ranges()),
                         '(0.5000-2.0000,2.0000-3.5000,3.5000-5.0000,)',
                         'Equal interval classification not correct')

        # Quantile classes
        renderer.updateClasses(ml, renderer.Quantile, 3)
        self.assertEqual(dumpRangeBreaks(renderer.ranges()),
                         '(0.5000-1.0000,1.0000-1.2000,1.2000-5.0000,)',
                         'Quantile classification not correct')
        renderer.updateClasses(ml, renderer.Quantile, 4)
        self.assertEqual(
            dumpRangeBreaks(renderer.ranges()),
            '(0.5000-1.0000,1.0000-1.1000,1.1000-1.2000,1.2000-5.0000,)',
            'Quantile classification not correct')
コード例 #16
0
    def add_symbology(self):
        low_color = self.color_low_value.color()
        high_color = self.color_high_value.color()
        index = self.cbx_mode.currentIndex()
        mode = self.cbx_mode.itemData(index)
        classes = self.spinBox_classes.value()

        # Compute renderer
        # noinspection PyArgumentList
        symbol = QgsSymbolV2.defaultSymbol(QGis.Polygon)

        color_ramp = QgsVectorGradientColorRampV2(low_color, high_color)
        # noinspection PyArgumentList
        renderer = QgsGraduatedSymbolRendererV2.createRenderer(
            self.output_layer,
            self.name_field,
            classes,
            mode,
            symbol,
            color_ramp)
        self.output_layer.setRendererV2(renderer)
コード例 #17
0
ファイル: utils.py プロジェクト: luipir/gem-mt
    def setGraduatedStyle(vl, ranges, field, **kwargs):
        """ set a graduated style """

        # make a symbol for each range
        rangeV2List = []
        for min_val, max_val, attrs in ranges:
            if 'label' in attrs:
                label = attrs['label']
            #elif min_val == None:
            #	label = u'%s <= %s' % (field, max_val)
            #elif max_val == None:
            #	label = u'%s > %s' % (field, min_val)
            else:
                label = u'%s < %s <= %s' % (min_val, field, max_val)

            symbolV2 = QgsSymbolV2.defaultSymbol(vl.geometryType())
            if 'color' in attrs:
                symbolV2.setColor(attrs['color'])
            if 'size' in attrs:
                symbolV2.setSize(attrs['size'])

            # from QGis > 1.8 QgsMarkerSymbolV2 has 2 scale methods: ScaleArea and ScaleDiameter
            if 'sizeScaleMethod' in kwargs and hasattr(symbolV2,
                                                       'setScaleMethod'):
                symbolV2.setScaleMethod(kwargs['sizeScaleMethod'])

            rangeV2 = QgsRendererRangeV2(min_val, max_val, symbolV2, label)
            rangeV2List.append(rangeV2)

        # create the renderer
        renderer = QgsGraduatedSymbolRendererV2(field, rangeV2List)

        # set size scale field
        if 'sizeScaleField' in kwargs:
            renderer.setSizeScaleField(kwargs['sizeScaleField'])

        # set the renderer for the layer
        vl.setRendererV2(renderer)
        Utils.iface.legendInterface().refreshLayerSymbology(vl)
コード例 #18
0
    def setVectorErosionStyle(self, layer):
        # define ranges: label, lower value, upper value, hex value of color
        g_values = (
            (self.tr('Very weakly endangered'), 0.0, 1.0, '#458b00'),
            (self.tr('Weakly endangered'), 1.0, 2.0, '#bcee68'),
            (self.tr('Moderately endangered'), 2.0, 4.0, '#eedd82'),
            (self.tr('Severely endangered'), 4.0, 8.0, '#ffa07a'),
            (self.tr('Very severely endangered'), 8.0, 10.0, '#ff4500'),
            (self.tr('Extremely endangered'), 10.0, 999999.9, '#8b2500'),
        )

        # create a category for each item in g_values
        ranges = []
        for label, lower, upper, color in g_values:
            symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
            symbol.setColor(QColor(color))
            rng = QgsRendererRangeV2(lower, upper, symbol, label)
            ranges.append(rng)

        # create the renderer and assign it to a layer
        expression = 'G'  # field name
        renderer = QgsGraduatedSymbolRendererV2(expression, ranges)
        layer.setRendererV2(renderer)
コード例 #19
0
    def updateSymbology(self):
        if self._layer and self._layer.isValid():
            att_values = [
                f[self.target_field]
                for f in self._layer.dataProvider().getFeatures()
            ]

            intervs = self._intervalValues(att_values)
            colors = self._colorValues()
            range_list = []
            for v_min, v_max, col in zip(intervs[:-1], intervs[1:], colors):
                symbol = QgsSymbolV2.defaultSymbol(self._layer.geometryType())
                symbol.setColor(col)
                symbol.setWidth(self.LINE_WIDTH_PIX)
                label = '{:0.2f}%->{:0.2f}%'.format(v_min, v_max)
                range_ = QgsRendererRangeV2(v_min, v_max, symbol, label)
                range_list.append(range_)

            renderer = QgsGraduatedSymbolRendererV2('', range_list)
            renderer.setMode(QgsGraduatedSymbolRendererV2.Custom)
            renderer.setClassAttribute(self.target_field)
            self._layer.setRendererV2(renderer)
            self._layer.triggerRepaint()
コード例 #20
0
    def setBpejStyle(self, layer):
        # define ranges: label, lower value, upper value, hex value of color
        k_values = (
            (self.tr('0.0-0.1'), 0.0, 0.1, '#458b00'),
            (self.tr('0.1-0.2'), 0.1, 0.2, '#bcee68'),
            (self.tr('0.2-0.3'), 0.2, 0.3, '#eedd82'),
            (self.tr('0.3-0.4'), 0.3, 0.4, '#ffa07a'),
            (self.tr('0.4-0.5'), 0.4, 0.5, '#ff4500'),
            (self.tr('0.5 and more'), 0.5, 9999.0, '#8b2500'),
        )

        # create a category for each item in k_values
        ranges = []
        for label, lower, upper, color in k_values:
            symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
            symbol.setColor(QColor(color))
            rng = QgsRendererRangeV2(lower, upper, symbol, label)
            ranges.append(rng)

        # create the renderer and assign it to a layer
        expression = 'K'  # field name
        renderer = QgsGraduatedSymbolRendererV2(expression, ranges)
        layer.setRendererV2(renderer)
コード例 #21
0
def applySymbologyFixedDivisions(layer, field):

    colors = field.get_colour_scale()
    ranges = field.get_values_ranges()
    labels = field.get_style_labels()
    column_name = field.ium_column
    #print colors, ranges, labels

    rangeList = []
    for i, range in enumerate(ranges):
        rangeList.append(
            makeSymbologyForRange(layer, range[0], range[1], labels[i],
                                  QColor(colors[i])))
    renderer = QgsGraduatedSymbolRendererV2(column_name, rangeList)
    for i in renderer.symbols():
        i.symbolLayer(0).setOutlineColor(QColor("#ffffff"))
        try:
            i.symbolLayer(0).setBorderWidth(0.000001)
        except AttributeError:  # if line layer
            pass
        #i.symbolLayer(0).setOutputUnit(1)
    renderer.setMode(QgsGraduatedSymbolRendererV2.Custom)
    layer.setRendererV2(renderer)
    return renderer
コード例 #22
0
    def testQgsGraduatedSymbolRendererV2_2(self):
        """Test QgsGraduatedSymbolRendererV2: Adding /removing/editing classes """
        # Create a renderer
        renderer = QgsGraduatedSymbolRendererV2()
        symbol = createMarkerSymbol()
        renderer.setSourceSymbol(symbol.clone())
        symbol.setColor(QColor(255, 0, 0))

        # Add class without start and end ranges

        renderer.addClass(symbol.clone())
        renderer.addClass(symbol.clone())
        renderer.updateRangeLabel(1, 'Second range')
        renderer.updateRangeLowerValue(1, 10.0)
        renderer.updateRangeUpperValue(1, 25.0)
        renderer.updateRangeRenderState(1, False)
        symbol.setColor(QColor(0, 0, 255))
        renderer.updateRangeSymbol(1, symbol.clone())

        # Add as a rangeobject
        symbol.setColor(QColor(0, 255, 0))
        range = QgsRendererRangeV2(20.0, 25.5, symbol.clone(), 'Third range', False)
        renderer.addClassRange(range)

        # Add class by lower and upper
        renderer.addClassLowerUpper(25.5, 30.5)
        # (Update label for sorting tests)
        renderer.updateRangeLabel(3, 'Another range')

        self.assertEqual(
            dumpRangeLabels(renderer.ranges()),
            '(0.0 - 0.0,Second range,Third range,Another range,)',
            'Added ranges labels not correct')
        self.assertEqual(
            dumpRangeBreaks(renderer.ranges()),
            '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)',
            'Added ranges lower/upper values not correct')

        # Check that clone function works

        renderer2 = renderer.clone()
        self.assertEqual(
            dumpGraduatedRenderer(renderer),
            dumpGraduatedRenderer(renderer2),
            "clone function doesn't replicate renderer properly"
        )

        # Check save and reload from Dom works

        doc = QDomDocument()
        element = renderer.save(doc)
        renderer2 = QgsGraduatedSymbolRendererV2.create(element)
        self.assertEqual(
            dumpGraduatedRenderer(renderer),
            dumpGraduatedRenderer(renderer2),
            "Save/create from DOM doesn't replicate renderer properly"
        )

        # Check sorting

        renderer.sortByLabel()
        self.assertEqual(
            dumpRangeList(renderer.ranges(), labelsOnly=True),
            '(0.0 - 0.0,Another range,Second range,Third range,)',
            'sortByLabel not correct')
        renderer.sortByValue()
        self.assertEqual(
            dumpRangeBreaks(renderer.ranges()),
            '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)',
            'sortByValue not correct')
        renderer.sortByValue(Qt.DescendingOrder)
        self.assertEqual(
            dumpRangeBreaks(renderer.ranges()),
            '(25.5000-30.5000,20.0000-25.5000,10.0000-25.0000,0.0000-0.0000,)',
            'sortByValue descending not correct')

        # Check deleting

        renderer.deleteClass(2)
        self.assertEqual(
            dumpRangeBreaks(renderer.ranges()),
            '(25.5000-30.5000,20.0000-25.5000,0.0000-0.0000,)',
            'deleteClass not correct')

        renderer.deleteAllClasses()
        self.assertEqual(len(renderer.ranges()), 0, "deleteAllClasses didn't delete all")
コード例 #23
0
def render_old(layer,field):

    myTargetField = field
    myRangeList = []
    myOpacity = 1
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FFFFFF'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(-150.0,0.0,mySymbol,"No level")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#C0FFC0'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(0.1,34.9,mySymbol,"< 35 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#00CC00'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(35.0,39.9,mySymbol,"35 - 40 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#005000'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(40.0,44.9,mySymbol,"40 - 45 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FFFF00'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(45.0,49.9,mySymbol,"45 - 50 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FFC74A'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(50.0,54.9,mySymbol,"50 - 55 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FF6600'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(55.0,59.9,mySymbol,"55 - 60 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FF3333'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(60.0,64.9,mySymbol,"60 - 65 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#990033'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(65.0,69.9,mySymbol,"65 - 70 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#AD9AD6'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(70.0,74.9,mySymbol,"70 - 75 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#0000FF'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(75.0,79.9,mySymbol,"75 - 80 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#000066'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(80.0,150.0,mySymbol,"> 80 dB(A)")
    myRangeList.append(myRange)
    
    myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList)
    myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
    myRenderer.setClassAttribute(myTargetField)
    
    layer.setRendererV2(myRenderer)
    iface.legendInterface().refreshLayerSymbology(layer)
    #layer.reload()
    #iface.mapCanvas().refresh()
    layer.triggerRepaint()
コード例 #24
0
def applyGraduatedSymbolRenderer(layer, fieldName):
    renderer = QgsGraduatedSymbolRendererV2()
    renderer.setClassAttribute(fieldName)
    layer.setRendererV2(renderer)
    layer.rendererV2().updateClasses(layer, QgsGraduatedSymbolRendererV2.Jenks,
                                     5)
コード例 #25
0
    def testQgsGraduatedSymbolRendererV2_1(self):
        """Test QgsGraduatedSymbolRendererV2: Basic get/set functions """

        # Create a renderer
        renderer = QgsGraduatedSymbolRendererV2()

        symbol = createMarkerSymbol()
        renderer.setSourceSymbol(symbol.clone())
        self.assertEqual(symbol.dump(),
                         renderer.sourceSymbol().dump(),
                         "Get/set renderer source symbol")

        attr = '"value"*"value"'
        renderer.setClassAttribute(attr)
        self.assertEqual(attr, renderer.classAttribute(),
                         "Get/set renderer class attribute")

        for m in (
                QgsGraduatedSymbolRendererV2.Custom,
                QgsGraduatedSymbolRendererV2.EqualInterval,
                QgsGraduatedSymbolRendererV2.Quantile,
                QgsGraduatedSymbolRendererV2.Jenks,
                QgsGraduatedSymbolRendererV2.Pretty,
                QgsGraduatedSymbolRendererV2.StdDev,
        ):
            renderer.setMode(m)
            self.assertEqual(m, renderer.mode(), "Get/set renderer mode")

        format = createLabelFormat()
        renderer.setLabelFormat(format)
        self.assertEqual(dumpLabelFormat(format),
                         dumpLabelFormat(renderer.labelFormat()),
                         "Get/set renderer label format")

        ramp = createColorRamp()
        renderer.setSourceColorRamp(ramp)
        self.assertEqual(dumpColorRamp(ramp),
                         dumpColorRamp(renderer.sourceColorRamp()),
                         "Get/set renderer color ramp")

        renderer.setInvertedColorRamp(True)
        self.assertTrue(renderer.invertedColorRamp(),
                        "Get/set renderer inverted color ramp")
        renderer.setInvertedColorRamp(False)
        self.assertFalse(renderer.invertedColorRamp(),
                         "Get/set renderer inverted color ramp")

        value = '"value"*2'
        exp = QgsSymbolLayerV2Utils.fieldOrExpressionToExpression(value)
        valuestr = QgsSymbolLayerV2Utils.fieldOrExpressionFromExpression(exp)
        renderer.setRotationField(value)
        self.assertEqual(valuestr, renderer.rotationField(),
                         "Get/set renderer rotation field")

        value = '"value"*3'
        exp = QgsSymbolLayerV2Utils.fieldOrExpressionToExpression(value)
        valuestr = QgsSymbolLayerV2Utils.fieldOrExpressionFromExpression(exp)
        renderer.setSizeScaleField(value)
        self.assertEqual(valuestr, renderer.sizeScaleField(),
                         "Get/set renderer size scale field")

        renderer.setSourceColorRamp(ramp)
        self.assertEqual(dumpColorRamp(ramp),
                         dumpColorRamp(renderer.sourceColorRamp()),
                         "Get/set renderer color ramp")

        for sm in (
                QgsSymbolV2.ScaleArea,
                QgsSymbolV2.ScaleDiameter,
        ):
            renderer.setScaleMethod(sm)
            self.assertEqual(str(sm), str(renderer.scaleMethod()),
                             "Get/set renderer scale method")
        # test for classificatio with varying size
        renderer.setGraduatedMethod(QgsGraduatedSymbolRendererV2.GraduatedSize)
        renderer.setSourceColorRamp(None)
        renderer.addClassLowerUpper(0, 2)
        renderer.addClassLowerUpper(2, 4)
        renderer.addClassLowerUpper(4, 6)
        renderer.setSymbolSizes(2, 13)
        self.assertEqual(renderer.maxSymbolSize(), 13)
        self.assertEqual(renderer.minSymbolSize(), 2)
        refSizes = [2, (13 + 2) * .5, 13]
        ctx = QgsRenderContext()
        for idx, symbol in enumerate(renderer.symbols(ctx)):
            self.assertEqual(symbol.size(), refSizes[idx])
コード例 #26
0
    def testQgsGraduatedSymbolRendererV2_2(self):
        """Test QgsGraduatedSymbolRendererV2: Adding /removing/editing classes """
        # Create a renderer
        renderer = QgsGraduatedSymbolRendererV2()
        symbol = createMarkerSymbol()
        renderer.setSourceSymbol(symbol.clone())
        symbol.setColor(QColor(255, 0, 0))

        # Add class without start and end ranges

        renderer.addClass(symbol.clone())
        renderer.addClass(symbol.clone())
        renderer.updateRangeLabel(1, 'Second range')
        renderer.updateRangeLowerValue(1, 10.0)
        renderer.updateRangeUpperValue(1, 25.0)
        renderer.updateRangeRenderState(1, False)
        symbol.setColor(QColor(0, 0, 255))
        renderer.updateRangeSymbol(1, symbol.clone())

        # Add as a rangeobject
        symbol.setColor(QColor(0, 255, 0))
        range = QgsRendererRangeV2(20.0, 25.5, symbol.clone(), 'Third range',
                                   False)
        renderer.addClassRange(range)

        # Add class by lower and upper
        renderer.addClassLowerUpper(25.5, 30.5)
        # (Update label for sorting tests)
        renderer.updateRangeLabel(3, 'Another range')

        self.assertEqual(
            dumpRangeLabels(renderer.ranges()),
            '(0.0 - 0.0,Second range,Third range,Another range,)',
            'Added ranges labels not correct')
        self.assertEqual(
            dumpRangeBreaks(renderer.ranges()),
            '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)',
            'Added ranges lower/upper values not correct')

        # Check that clone function works

        renderer2 = renderer.clone()
        self.assertEqual(dumpGraduatedRenderer(renderer),
                         dumpGraduatedRenderer(renderer2),
                         "clone function doesn't replicate renderer properly")

        # Check save and reload from Dom works

        doc = QDomDocument()
        element = renderer.save(doc)
        renderer2 = QgsGraduatedSymbolRendererV2.create(element)
        self.assertEqual(
            dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2),
            "Save/create from DOM doesn't replicate renderer properly")

        # Check sorting

        renderer.sortByLabel()
        self.assertEqual(
            dumpRangeList(renderer.ranges(), labelsOnly=True),
            '(0.0 - 0.0,Another range,Second range,Third range,)',
            'sortByLabel not correct')
        renderer.sortByValue()
        self.assertEqual(
            dumpRangeBreaks(renderer.ranges()),
            '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)',
            'sortByValue not correct')
        renderer.sortByValue(Qt.DescendingOrder)
        self.assertEqual(
            dumpRangeBreaks(renderer.ranges()),
            '(25.5000-30.5000,20.0000-25.5000,10.0000-25.0000,0.0000-0.0000,)',
            'sortByValue descending not correct')

        # Check deleting

        renderer.deleteClass(2)
        self.assertEqual(dumpRangeBreaks(renderer.ranges()),
                         '(25.5000-30.5000,20.0000-25.5000,0.0000-0.0000,)',
                         'deleteClass not correct')

        renderer.deleteAllClasses()
        self.assertEqual(len(renderer.ranges()), 0,
                         "deleteAllClasses didn't delete all")
コード例 #27
0
    def style_maps(self, layer=None, style_by=None):
        if layer is None:
            layer = self.layer
        if style_by is None:
            style_by = self.default_field_name
        symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
        # see properties at:
        # https://qgis.org/api/qgsmarkersymbollayerv2_8cpp_source.html#l01073
        symbol.setAlpha(1)  # opacity
        if isinstance(symbol, QgsMarkerSymbolV2):
            # do it only for the layer with points
            self._set_symbol_size(symbol)
            symbol.symbolLayer(0).setOutlineStyle(Qt.PenStyle(Qt.NoPen))

        style = get_style(layer, self.iface.messageBar())

        # this is the default, as specified in the user settings
        ramp = QgsVectorGradientColorRampV2(style['color_from'],
                                            style['color_to'])
        mode = style['mode']

        # in most cases, we override the user-specified setting, and use
        # instead a setting that was required by scientists
        if self.output_type in OQ_TO_LAYER_TYPES:
            default_qgs_style = QgsStyleV2().defaultStyle()
            default_color_ramp_names = default_qgs_style.colorRampNames()
            if self.output_type in ('dmg_by_asset', 'losses_by_asset',
                                    'avg_losses-stats'):
                # options are EqualInterval, Quantile, Jenks, StdDev, Pretty
                # jenks = natural breaks
                mode = QgsGraduatedSymbolRendererV2.Jenks
                ramp_type_idx = default_color_ramp_names.index('Reds')
                inverted = False
            elif self.output_type in ('hmaps', 'gmf_data', 'ruptures'):
                # options are EqualInterval, Quantile, Jenks, StdDev, Pretty
                if self.output_type == 'ruptures':
                    mode = QgsGraduatedSymbolRendererV2.Pretty
                else:
                    mode = QgsGraduatedSymbolRendererV2.EqualInterval
                ramp_type_idx = default_color_ramp_names.index('Spectral')
                inverted = True
            ramp = default_qgs_style.colorRamp(
                default_color_ramp_names[ramp_type_idx])
        graduated_renderer = QgsGraduatedSymbolRendererV2.createRenderer(
            layer,
            style_by,
            style['classes'],
            mode,
            symbol,
            ramp,
            inverted=inverted)
        label_format = graduated_renderer.labelFormat()
        # label_format.setTrimTrailingZeroes(True)  # it might be useful
        label_format.setPrecision(2)
        graduated_renderer.setLabelFormat(label_format, updateRanges=True)
        # add a class for 0 values, unless while styling ruptures
        if self.output_type != 'ruptures':
            VERY_SMALL_VALUE = 1e-20
            graduated_renderer.updateRangeLowerValue(0, VERY_SMALL_VALUE)
            symbol_zeros = QgsSymbolV2.defaultSymbol(layer.geometryType())
            symbol_zeros.setColor(QColor(240, 240, 240))  # very light grey
            if isinstance(symbol, QgsMarkerSymbolV2):
                # do it only for the layer with points
                self._set_symbol_size(symbol_zeros)
                symbol_zeros.symbolLayer(0).setOutlineStyle(
                    Qt.PenStyle(Qt.NoPen))
            zeros_min = 0.0
            zeros_max = VERY_SMALL_VALUE
            range_zeros = QgsRendererRangeV2(
                zeros_min, zeros_max, symbol_zeros,
                " %.2f - %.2f" % (zeros_min, zeros_max), True)
            graduated_renderer.addClassRange(range_zeros)
            graduated_renderer.moveClass(
                len(graduated_renderer.ranges()) - 1, 0)
        layer.setRendererV2(graduated_renderer)
        layer.setLayerTransparency(30)  # percent
        layer.triggerRepaint()
        self.iface.legendInterface().refreshLayerSymbology(layer)
        self.iface.mapCanvas().refresh()
コード例 #28
0
ファイル: styling.py プロジェクト: roscoeKartoza/inasafe
def set_vector_graduated_style(vector_layer, style):
    """Set graduated QGIS vector style based on InaSAFE style dictionary.

    For **opaque** a value of **0** can be used. For **fully transparent**, a
    value of **100** can be used. The calling function should take care to
    scale the transparency level to between 0 and 100.

    :param vector_layer: A QGIS vector layer that will be styled.
    :type vector_layer: QgsVectorLayer, QgsMapLayer

    :param style: Dictionary of the form as in the example below
    :type style: dict

    :returns: None - Sets and saves style for vector_layer

    Example style::

        {'target_field': 'DMGLEVEL',
        'style_classes':
        [{'transparency': 1, 'max': 1.5, 'colour': '#fecc5c',
          'min': 0.5, 'label': '[0.5 - 1.5] Low damage', 'size' : 1},
        {'transparency': 55, 'max': 2.5, 'colour': '#fd8d3c',
         'min': 1.5, 'label': '[1.5 - 2.5] Medium damage', 'size' : 1},
        {'transparency': 80, 'max': 3.5, 'colour': '#f31a1c',
         'min': 2.5, 'label': '[2.5 - 3.5] High damage', 'size' : 1}]}

    .. note:: The transparency and size keys are optional. Size applies
       to points only.

    .. note:: you can optionally pass border_color also, if not color will be
        used

    .. note:: you can optionally pass data_defined also, this has to be a
        dictionary of property: expressions like
        {'color': 'color_hsv(%s, "pop"/%s*100, %s)' % (hue, max, val)}
    """
    target_field = style['target_field']
    style_classes = style['style_classes']
    geometry_type = vector_layer.geometryType()

    range_list = []
    for style_class in style_classes:
        # Transparency 100: transparent
        # Transparency 0: opaque
        size = 2  # mm
        if 'size' in style_class:
            size = style_class['size']
        transparency_percent = 0
        if 'transparency' in style_class:
            transparency_percent = style_class['transparency']

        if 'min' not in style_class:
            raise StyleError('Style info should provide a "min" entry')
        if 'max' not in style_class:
            raise StyleError('Style info should provide a "max" entry')

        try:
            min_val = float(style_class['min'])
        except TypeError:
            raise StyleError('Class break lower bound should be a number.'
                             'I got %s' % style_class['min'])

        try:
            max_val = float(style_class['max'])
        except TypeError:
            raise StyleError('Class break upper bound should be a number.'
                             'I got %s' % style_class['max'])

        color = style_class['colour']
        label = style_class['label']
        color = QtGui.QColor(color)
        # noinspection PyArgumentList
        symbol = QgsSymbolV2.defaultSymbol(geometry_type)
        # We need to create a custom symbol layer as
        # the border colour of a symbol can not be set otherwise
        # noinspection PyArgumentList
        try:
            value = style_class['border_color']
            border_color = QtGui.QColor(value)
        except KeyError:
            border_color = color

        if geometry_type == QGis.Point:
            symbol_layer = QgsSimpleMarkerSymbolLayerV2()
            symbol_layer.setBorderColor(border_color)
            symbol_layer.setSize(size)
            symbol.changeSymbolLayer(0, symbol_layer)
        elif geometry_type == QGis.Polygon:
            symbol_layer = QgsSimpleFillSymbolLayerV2()
            symbol_layer.setBorderColor(border_color)
            symbol.changeSymbolLayer(0, symbol_layer)
        else:
            # for lines we do nothing special as the property setting
            # below should give us what we require.
            pass

        try:
            value = style_class['border_wdth']
            symbol_layer.setBorderWidth(value)
        except (NameError, KeyError):
            # use QGIS default border size
            # NameError is when symbol_layer is not defined (lines for example)
            # KeyError is when borderWidth is not defined
            if hasattr(symbol_layer, 'setBorderWidth') and \
                    geometry_type == QGis.Polygon:
                symbol_layer.setBorderWidth(0)

        # set data defined properties
        try:
            for prop, expr in style_class['data_defined'].iteritems():
                symbol_layer.setDataDefinedProperty(prop, expr)
        except (NameError, KeyError):
            # NameError is when symbol_layer is not defined (lines for example)
            # KeyError is when data_defined is not defined
            pass

        symbol.setColor(color)
        # .. todo:: Check that vectors use alpha as % otherwise scale TS
        # Convert transparency % to opacity
        # alpha = 0: transparent
        # alpha = 1: opaque
        alpha = 1 - transparency_percent / 100.0
        symbol.setAlpha(alpha)
        range_renderer = QgsRendererRangeV2(min_val, max_val, symbol, label)
        range_list.append(range_renderer)

    renderer = QgsGraduatedSymbolRendererV2('', range_list)
    renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
    renderer.setClassAttribute(target_field)
    vector_layer.setRendererV2(renderer)
    vector_layer.saveDefaultStyle()
コード例 #29
0
def render(layer,field):

    myTargetField = field
    myRangeList = []
    myOpacity = 1

    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#D8D8D8'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(-150.0,0.0,mySymbol,"No level")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FFFFFF'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(0.1,34.4,mySymbol,"< 35 dB(A)")
    myRangeList.append(myRange)    
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#238443'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(34.5,39.4,mySymbol,"35 - 39 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#78C679'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(39.5,44.4,mySymbol,"40 - 44 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#C2E699'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(44.5,49.4,mySymbol,"45 - 49 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FFFFB2'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(49.5,54.4,mySymbol,"50 - 54 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FECC5C'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(54.5,59.4,mySymbol,"55 - 59 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FD8D3C'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(59.5,64.4,mySymbol,"60 - 64 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#FF0909'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(64.5,69.4,mySymbol,"65 - 69 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#B30622'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(69.5,74.4,mySymbol,"70 - 74 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#67033B'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(74.5,79.4,mySymbol,"75 - 79 dB(A)")
    myRangeList.append(myRange)
    # symbol
    mySymbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    mySymbol.setColor(QColor('#1C0054'))
    mySymbol.setAlpha(myOpacity)
    myRange = QgsRendererRangeV2(79.5,150.0,mySymbol,">= 80 dB(A)")
    myRangeList.append(myRange)
    
    myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList)
    myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
    myRenderer.setClassAttribute(myTargetField)
    
    layer.setRendererV2(myRenderer)
    iface.legendInterface().refreshLayerSymbology(layer)
    #layer.reload()
    #iface.mapCanvas().refresh()
    layer.triggerRepaint()
コード例 #30
0
    def compute_and_display_cadastral_vulnerability(self, cadastral_layer,
                                                    output_grid_points,
                                                    output_cadastral_points,
                                                    crop_index, crop_name,
                                                    base_path):
        cadastral_points_per_plot = {}
        for p in (output_grid_points + output_cadastral_points):
            if p.cadastral_polygon is None: continue
            if p.lulc_type not in ['agriculture', 'fallow land']: continue
            if p.cadastral_polygon.id() in cadastral_points_per_plot:
                cadastral_points_per_plot[p.cadastral_polygon.id()].append(
                    p.budget.PET_minus_AET_crop_end[crop_index])
            else:
                cadastral_points_per_plot[p.cadastral_polygon.id()] = [
                    p.budget.PET_minus_AET_crop_end[crop_index]
                ]
        for k, v in cadastral_points_per_plot.items():
            if len(v) > 0:
                cadastral_points_per_plot[k] = sum(v) / len(v)
            else:
                del cadastral_points_per_plot[k]

        # print cadastral_points_per_plot
        #	Create duplicate cadastral layer in memory
        memory_cadastral_layer = QgsVectorLayer(
            'Polygon?crs=epsg:32643',
            crop_name + ' Cadastral Level Vulnerability', 'memory')
        memory_cadastral_layer.startEditing()
        memory_cadastral_layer.dataProvider().addAttributes(
            cadastral_layer.qgsLayer.dataProvider().fields().toList())
        memory_cadastral_layer.updateFields()
        dict_new_feature_id_to_old_feature_id = {}
        for old_plot_id in cadastral_points_per_plot:
            result, output_features = memory_cadastral_layer.dataProvider(
            ).addFeatures([cadastral_layer.feature_dict[old_plot_id]])
            dict_new_feature_id_to_old_feature_id[
                output_features[0].id()] = old_plot_id
        memory_cadastral_layer.dataProvider().addAttributes(
            [QgsField('Deficit', QVariant.Double)])
        memory_cadastral_layer.updateFields()
        for new_feature in memory_cadastral_layer.getFeatures():
            new_feature['Deficit'] = cadastral_points_per_plot[
                dict_new_feature_id_to_old_feature_id[new_feature.id()]]
            memory_cadastral_layer.updateFeature(new_feature)
        memory_cadastral_layer.commitChanges()

        #	Graduated Rendering
        graduated_symbol_renderer_range_list = []
        ET_D_max = max(cadastral_points_per_plot.values())
        opacity = 1
        geometry_type = memory_cadastral_layer.geometryType()
        intervals_count = CADASTRAL_VULNERABILITY_DISPLAY_COLOUR_INTERVALS_COUNT
        dict_interval_colour = CADASTRAL_VULNERABILITY_DISPLAY_COLOURS_DICT
        for i in range(intervals_count):
            interval_min = 0 if i == 0 else (ET_D_max * float(i) /
                                             intervals_count) + 0.01
            interval_max = ET_D_max * float(i + 1) / intervals_count
            label = "{0:.2f} - {1:.2f}".format(interval_min, interval_max)
            colour = QColor(*dict_interval_colour[i])
            symbol = QgsSymbolV2.defaultSymbol(geometry_type)
            symbol.setColor(colour)
            symbol.setAlpha(opacity)
            interval_range = QgsRendererRangeV2(interval_min, interval_max,
                                                symbol, label)
            graduated_symbol_renderer_range_list.append(interval_range)
        renderer = QgsGraduatedSymbolRendererV2(
            '', graduated_symbol_renderer_range_list)
        renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
        renderer.setClassAttribute('Deficit')
        memory_cadastral_layer.setRendererV2(renderer)

        QgsMapLayerRegistry.instance().addMapLayer(memory_cadastral_layer)
        memory_cadastral_layer.setCustomProperty('labeling', 'pal')
        memory_cadastral_layer.setCustomProperty('labeling/enabled', 'true')
        memory_cadastral_layer.setCustomProperty('labeling/fieldName',
                                                 'Number')
        memory_cadastral_layer.setCustomProperty('labeling/fontSize', '10')
        memory_cadastral_layer.setCustomProperty('labeling/placement', '0')

        memory_cadastral_layer.dataProvider().forceReload()
        memory_cadastral_layer.triggerRepaint()

        QgsVectorFileWriter.writeAsVectorFormat(
            memory_cadastral_layer, base_path + '/kharif_' + crop_name +
            '_cadastral_level_vulnerability.shp', "utf-8", None,
            "ESRI Shapefile")
コード例 #31
0
def setVectorStyle(theQgisVectorLayer, theStyle):
    """Set QGIS vector style based on InaSAFE style dictionary.

    For **opaque** a value of **0** can be used. For **fully transparent**, a
    value of **100** can be used. The function should take care to scale the
    transparency level to between 0 and 100.

    Args:
        * theQgisVectorLayer: QgsMapLayer
        * theStyle: dict - Dictionary of the form as in the example below

    Returns:
        None - Sets and saves style for theQgisVectorLayer

    Raises:
        None

    Example:

        {'target_field': 'DMGLEVEL',
        'style_classes':
        [{'transparency': 1, 'max': 1.5, 'colour': '#fecc5c',
          'min': 0.5, 'label': 'Low damage', 'size' : 1},
        {'transparency': 55, 'max': 2.5, 'colour': '#fd8d3c',
         'min': 1.5, 'label': 'Medium damage', 'size' : 1},
        {'transparency': 80, 'max': 3.5, 'colour': '#f31a1c',
         'min': 2.5, 'label': 'High damage', 'size' : 1}]}

        .. note:: The transparency and size keys are optional. Size applies
           to points only.

    """
    myTargetField = theStyle['target_field']
    myClasses = theStyle['style_classes']
    myGeometryType = theQgisVectorLayer.geometryType()

    myRangeList = []
    for myClass in myClasses:
        # Transparency 100: transparent
        # Transparency 0: opaque
        mySize = 2  # mm
        if 'size' in myClass:
            mySize = myClass['size']
        myTransparencyPercent = 0
        if 'transparency' in myClass:
            myTransparencyPercent = myClass['transparency']

        if 'min' not in myClass:
            raise StyleError('Style info should provide a "min" entry')
        if 'max' not in myClass:
            raise StyleError('Style info should provide a "max" entry')

        try:
            myMin = float(myClass['min'])
        except TypeError:
            raise StyleError('Class break lower bound should be a number.'
                             'I got %s' % myClass['min'])

        try:
            myMax = float(myClass['max'])
        except TypeError:
            raise StyleError('Class break upper bound should be a number.'
                             'I got %s' % myClass['max'])

        myColour = myClass['colour']
        myLabel = myClass['label']
        myColour = QtGui.QColor(myColour)
        mySymbol = QgsSymbolV2.defaultSymbol(myGeometryType)
        myColourString = "%s, %s, %s" % (myColour.red(), myColour.green(),
                                         myColour.blue())
        # Work around for the fact that QgsSimpleMarkerSymbolLayerV2
        # python bindings are missing from the QGIS api.
        # .. see:: http://hub.qgis.org/issues/4848
        # We need to create a custom symbol layer as
        # the border colour of a symbol can not be set otherwise
        myRegistry = QgsSymbolLayerV2Registry.instance()
        if myGeometryType == QGis.Point:
            myMetadata = myRegistry.symbolLayerMetadata('SimpleMarker')
            # note that you can get a list of available layer properties
            # that you can set by doing e.g.
            # QgsSimpleMarkerSymbolLayerV2.properties()
            mySymbolLayer = myMetadata.createSymbolLayer(
                {'color_border': myColourString})
            mySymbolLayer.setSize(mySize)
            mySymbol.changeSymbolLayer(0, mySymbolLayer)
        elif myGeometryType == QGis.Polygon:
            myMetadata = myRegistry.symbolLayerMetadata('SimpleFill')
            mySymbolLayer = myMetadata.createSymbolLayer(
                {'color_border': myColourString})
            mySymbol.changeSymbolLayer(0, mySymbolLayer)
        else:
            # for lines we do nothing special as the property setting
            # below should give us what we require.
            pass

        mySymbol.setColor(myColour)
        # .. todo:: Check that vectors use alpha as % otherwise scale TS
        # Convert transparency % to opacity
        # alpha = 0: transparent
        # alpha = 1: opaque
        alpha = 1 - myTransparencyPercent / 100.0
        mySymbol.setAlpha(alpha)
        myRange = QgsRendererRangeV2(myMin, myMax, mySymbol, myLabel)
        myRangeList.append(myRange)

    myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList)
    myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
    myRenderer.setClassAttribute(myTargetField)
    theQgisVectorLayer.setRendererV2(myRenderer)
    theQgisVectorLayer.saveDefaultStyle()
コード例 #32
0
ファイル: styling.py プロジェクト: vdeparday/inasafe
def set_vector_graduated_style(vector_layer, style):
    """Set graduated QGIS vector style based on InaSAFE style dictionary.

    For **opaque** a value of **0** can be used. For **fully transparent**, a
    value of **100** can be used. The calling function should take care to
    scale the transparency level to between 0 and 100.

    :param vector_layer: A QGIS vector layer that will be styled.
    :type vector_layer: QgsVectorLayer, QgsMapLayer

    :param style: Dictionary of the form as in the example below
    :type style: dict

    :returns: None - Sets and saves style for vector_layer

    Example style::

        {'target_field': 'DMGLEVEL',
        'style_classes':
        [{'transparency': 1, 'max': 1.5, 'colour': '#fecc5c',
          'min': 0.5, 'label': '[0.5 - 1.5] Low damage', 'size' : 1},
        {'transparency': 55, 'max': 2.5, 'colour': '#fd8d3c',
         'min': 1.5, 'label': '[1.5 - 2.5] Medium damage', 'size' : 1},
        {'transparency': 80, 'max': 3.5, 'colour': '#f31a1c',
         'min': 2.5, 'label': '[2.5 - 3.5] High damage', 'size' : 1}]}

    .. note:: The transparency and size keys are optional. Size applies
       to points only.
    """
    myTargetField = style['target_field']
    myClasses = style['style_classes']
    myGeometryType = vector_layer.geometryType()

    myRangeList = []
    for myClass in myClasses:
        # Transparency 100: transparent
        # Transparency 0: opaque
        mySize = 2  # mm
        if 'size' in myClass:
            mySize = myClass['size']
        myTransparencyPercent = 0
        if 'transparency' in myClass:
            myTransparencyPercent = myClass['transparency']

        if 'min' not in myClass:
            raise StyleError('Style info should provide a "min" entry')
        if 'max' not in myClass:
            raise StyleError('Style info should provide a "max" entry')

        try:
            myMin = float(myClass['min'])
        except TypeError:
            raise StyleError('Class break lower bound should be a number.'
                             'I got %s' % myClass['min'])

        try:
            myMax = float(myClass['max'])
        except TypeError:
            raise StyleError('Class break upper bound should be a number.'
                             'I got %s' % myClass['max'])

        myColour = myClass['colour']
        myLabel = myClass['label']
        myColour = QtGui.QColor(myColour)
        # noinspection PyArgumentList
        mySymbol = QgsSymbolV2.defaultSymbol(myGeometryType)
        # We need to create a custom symbol layer as
        # the border colour of a symbol can not be set otherwise
        # noinspection PyArgumentList
        if myGeometryType == QGis.Point:
            mySymbolLayer = QgsSimpleMarkerSymbolLayerV2()
            mySymbolLayer.setBorderColor(myColour)
            mySymbolLayer.setSize(mySize)
            mySymbol.changeSymbolLayer(0, mySymbolLayer)
        elif myGeometryType == QGis.Polygon:
            mySymbolLayer = QgsSimpleFillSymbolLayerV2()
            mySymbolLayer.setBorderColor(myColour)
            mySymbol.changeSymbolLayer(0, mySymbolLayer)
        else:
            # for lines we do nothing special as the property setting
            # below should give us what we require.
            pass

        mySymbol.setColor(myColour)
        # .. todo:: Check that vectors use alpha as % otherwise scale TS
        # Convert transparency % to opacity
        # alpha = 0: transparent
        # alpha = 1: opaque
        alpha = 1 - myTransparencyPercent / 100.0
        mySymbol.setAlpha(alpha)
        myRange = QgsRendererRangeV2(myMin, myMax, mySymbol, myLabel)
        myRangeList.append(myRange)

    myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList)
    myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
    myRenderer.setClassAttribute(myTargetField)
    vector_layer.setRendererV2(myRenderer)
    vector_layer.saveDefaultStyle()
コード例 #33
0
    def run(self):
        """Run method that performs all the real work"""

        #~path = 'C:/Users/Sudhanshu/Downloads/Hivre_Bajar'
        #~ path = 'C:/Users/Rahul/Desktop/Gondala1'
        #~ path = 'C:/Users/Rahul/Desktop/BW_new'
        path = ''
        debugging = path != ''
        if debugging:
            zones_layer = self.iface.addVectorLayer(path + '/Zones.shp',
                                                    'Zones', 'ogr')
            soil_layer = self.iface.addVectorLayer(path + '/Soil.shp',
                                                   'Soil Cover', 'ogr')
            lulc_layer = self.iface.addVectorLayer(path + '/LULC.shp',
                                                   'Land-Use-Land-Cover',
                                                   'ogr')
            cadastral_layer = self.iface.addVectorLayer(
                path + '/Cadastral.shp', 'Cadastral Map', 'ogr')
            slope_layer = self.iface.addRasterLayer(path + '/Slope.tif',
                                                    'Slope')
            #~ drainage_layer = self.iface.addRasterLayer(path + '/Drainage.shp', 'Drainage', 'ogr')

            rainfall_csv = path + '/Rainfall.csv'
            sowing_threshold = 30
            crop = 'soyabean'
            interval_points = [50, 100]
            monsoon_end_date_index = MONSOON_END_DATE_INDEX

        else:
            self.dlg.show()
            if self.dlg.exec_() == QFileDialog.Rejected: return

            path = self.dlg.folder_path.text()
            zones_layer = self.iface.addVectorLayer(
                self.dlg.zones_layer_filename.text(), 'Zones', 'ogr')
            soil_layer = self.iface.addVectorLayer(
                self.dlg.soil_layer_filename.text(), 'Soil Cover', 'ogr')
            lulc_layer = self.iface.addVectorLayer(
                self.dlg.lulc_layer_filename.text(), 'Land-Use-Land-Cover',
                'ogr')
            cadastral_layer = self.iface.addVectorLayer(
                self.dlg.cadastral_layer_filename.text(), 'Cadastral Map',
                'ogr')
            slope_layer = self.iface.addRasterLayer(
                self.dlg.slope_layer_filename.text(), 'Slope')
            if self.dlg.drainage_layer_filename.text() != '':
                drainage_layer = self.iface.addRasterLayer(
                    self.dlg.drainage_layer_filename.text(), 'Drainage', 'ogr')

            rainfall_csv = self.dlg.rainfall_csv_filename.text()
            sowing_threshold = self.dlg.sowing_threshold.value()
            monsoon_end_date_index = self.dlg.monsoon_end.value() + 123
            crop = self.dlg.crop_combo_box.currentText()
            interval_points = [
                int(
                    self.dlg.colour_code_intervals_list_widget.item(
                        i).text().split('-')[0])
                for i in range(
                    1, self.dlg.colour_code_intervals_list_widget.count())
            ]

            #~ print path, zones_layer, soil_layer, lulc_layer, cadastral_layer, slope_layer, drainage_layer, rainfall_csv

        #~ start_qdate = self.dlg.from_date_edit.date()
        #~ date_with_index_0 = QDate(start_qdate.year(), 6, 1).dayOfYear()
        #~ start_date_index = start_qdate.dayOfYear() - date_with_index_0
        #~ end_qdate = self.dlg.to_date_edit.date()
        #~ end_date_index = end_qdate.dayOfYear() - date_with_index_0

        pointwise_output_csv_filename = '/kharif_model_pointwise_output.csv'
        zonewise_budget_csv_filename = '/kharif_model_zonewise_budget.csv'
        zonewise_budget_csv_filename_LU = '/kharif_model_zonewise_LU_budget.csv'
        zonewise_budget_areawise_csv_filename = '/kharif_model_zonewise_budget_area.csv'
        cadastral_vulnerability_csv_filename = '/kharif_model_cadastral_vulnerability.csv'
        model_calculator = KharifModelCalculator(path, zones_layer, soil_layer,
                                                 lulc_layer, cadastral_layer,
                                                 slope_layer, rainfall_csv)

        model_calculator.calculate(crop, pointwise_output_csv_filename,
                                   zonewise_budget_csv_filename,
                                   zonewise_budget_csv_filename_LU,
                                   zonewise_budget_areawise_csv_filename,
                                   cadastral_vulnerability_csv_filename,
                                   sowing_threshold, monsoon_end_date_index)
        uri = 'file:///' + path + pointwise_output_csv_filename + '?delimiter=%s&crs=epsg:32643&xField=%s&yField=%s' % (
            ',', 'X', 'Y')
        kharif_model_output_layer = QgsVectorLayer(uri, 'Kharif Model Output',
                                                   'delimitedtext')
        graduated_symbol_renderer_range_list = []
        ET_D_max = max([
            point.budget.PET_minus_AET_crop_end
            for point in model_calculator.output_grid_points
        ])
        opacity = 1
        intervals_count = self.dlg.colour_code_intervals_list_widget.count()
        for i in range(intervals_count):
            percent_interval_start_text, percent_interval_end_text = self.dlg.colour_code_intervals_list_widget.item(
                i).text().split('-')
            interval_min = 0 if percent_interval_start_text == '0' else (
                int(percent_interval_start_text) * ET_D_max / 100.0 + 0.01)
            interval_max = (int(percent_interval_end_text) * ET_D_max / 100.0)
            label = "{0:.2f} - {1:.2f}".format(interval_min, interval_max)
            colour = QColor(
                int(255 * (1 - (i + 1.0) / (intervals_count + 1.0))), 0,
                0)  # +1 done to tackle boundary cases
            symbol = QgsSymbolV2.defaultSymbol(
                kharif_model_output_layer.geometryType())
            symbol.setColor(colour)
            symbol.setAlpha(opacity)
            interval_range = QgsRendererRangeV2(interval_min, interval_max,
                                                symbol, label)
            graduated_symbol_renderer_range_list.append(interval_range)
        renderer = QgsGraduatedSymbolRendererV2(
            '', graduated_symbol_renderer_range_list)
        renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
        renderer.setClassAttribute('Crop duration PET-AET')
        kharif_model_output_layer.setRendererV2(renderer)
        QgsMapLayerRegistry.instance().addMapLayer(kharif_model_output_layer)

        QgsVectorFileWriter.writeAsVectorFormat(
            kharif_model_output_layer, path + '/kharif_et_deficit.shp',
            "utf-8", None, "ESRI Shapefile")

        #Dislpaying for long kharif crops
        if (crop in long_kharif_crops):
            kharif_model_monsoon_end_output_layer = QgsVectorLayer(
                uri, 'Kharif Model Monsoon End Output', 'delimitedtext')
            graduated_symbol_renderer_range_list = []
            ET_D_max = max([
                point.budget.PET_minus_AET_monsoon_end
                for point in model_calculator.output_grid_points
            ])
            opacity = 1
            intervals_count = self.dlg.colour_code_intervals_list_widget.count(
            )
            geometry_type = kharif_model_monsoon_end_output_layer.geometryType(
            )
            for i in range(intervals_count):
                percent_interval_start_text, percent_interval_end_text = self.dlg.colour_code_intervals_list_widget.item(
                    i).text().split('-')
                interval_min = 0 if percent_interval_start_text == '0' else (
                    int(percent_interval_start_text) * ET_D_max / 100.0 + 0.01)
                interval_max = (int(percent_interval_end_text) * ET_D_max /
                                100.0)
                label = "{0:.2f} - {1:.2f}".format(interval_min, interval_max)
                colour = QColor(
                    int(255 * (1 - (i + 1.0) / (intervals_count + 1.0))), 0,
                    0)  # +1 done to tackle boundary cases
                symbol = QgsSymbolV2.defaultSymbol(geometry_type)
                symbol.setColor(colour)
                symbol.setAlpha(opacity)
                interval_range = QgsRendererRangeV2(interval_min, interval_max,
                                                    symbol, label)
                graduated_symbol_renderer_range_list.append(interval_range)
            renderer = QgsGraduatedSymbolRendererV2(
                '', graduated_symbol_renderer_range_list)
            renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
            renderer.setClassAttribute('Monsoon PET-AET')
            kharif_model_monsoon_end_output_layer.setRendererV2(renderer)
            QgsMapLayerRegistry.instance().addMapLayer(
                kharif_model_monsoon_end_output_layer)
            QgsVectorFileWriter.writeAsVectorFormat(
                kharif_model_monsoon_end_output_layer,
                path + '/kharif_post_monsoon_et_deficit.shp', "utf-8", None,
                "ESRI Shapefile")

        self.iface.actionHideAllLayers().trigger()
        self.iface.legendInterface().setLayerVisible(zones_layer, True)
        if 'drainage_layer' in locals():
            self.iface.legendInterface().setLayerVisible(drainage_layer, True)
        if (crop in long_kharif_crops):
            self.iface.legendInterface().setLayerVisible(
                kharif_model_monsoon_end_output_layer, True)
        self.iface.legendInterface().setLayerVisible(kharif_model_output_layer,
                                                     True)
        self.iface.mapCanvas().setExtent(zones_layer.extent())
        self.iface.mapCanvas().mapRenderer().setDestinationCrs(
            zones_layer.crs())

        self.iface.mapCanvas().refresh()

        if self.dlg.save_image_group_box.isChecked():
            QTimer.singleShot(
                1000, lambda: self.iface.mapCanvas().saveAsImage(
                    self.dlg.save_image_filename.text()))