3

I have a bunch of shapefiles with multiple polylines. Each consistst of 5 up to 30 polylines. I would like to define a style which colours them alternating two colours.

When I use the Categorized style and define a colour ramp of two colours I get the first 10 polylines in blue and the next 10 in red. Is there an easy way to do this or should I manually create a rule-based style in which all odd numbers are red and all even numbers are blue?

2 Answers 2

4

I prefer using the following expressions, which contain the modulus operator, for rule-based styling to determine if a value is even or odd:

  • Even:

    "id" % 2 = 0
    
  • Odd

    "id" % 2 != 0
    

If you want to create a categorised style, you could use a little bit of Python by using the following in the Python Console:

from PyQt4.QtGui import QColor

layer = iface.activeLayer()
idx = layer.fieldNameIndex('id')
style_dict = {}

for feat in layer.getFeatures():
    if feat[idx] % 2 == 0:
        style_dict[(feat[idx])] = ('#ff0000', str(feat[idx]))
    else:
        style_dict[(feat[idx])] = ('#46add4', str(feat[idx]))

categories = []
for name, (color, label) in style_dict.items():
    symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    symbol.setColor(QColor(color))
    category = QgsRendererCategoryV2(name, symbol, label)
    categories.append(category)

field = 'id' 
renderer = QgsCategorizedSymbolRendererV2(field, categories)
layer.setRendererV2(renderer)
layer.triggerRepaint()

Example:

Result


In my opinion, depending on how many values you have, a rule-based style as you have used may not only be easier to create but also more easy on the eyes ;)

3

The only thing I have come up with so far is to make a rule-based style with 1 selecting odd and other selecting even id's:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.