I have a huge shapefile with an attribute field called category.
How do I add random individual colors to this category attribute and then export it with the style so that I can open it in other software?
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communityI have a huge shapefile with an attribute field called category.
How do I add random individual colors to this category attribute and then export it with the style so that I can open it in other software?
There might be a better way to do it, but here is my take on this. It is assuming your category field is called "code". All you have to do is create a dictionary with your random colors based on category field and store values in a new field "Color". Then you can use that to create a categorized renderer for your layer. Now the color is part of your shapefile and could probably be used in a different software. I hope this helps.
# import modules
import random
from qgis.core import *
from qgis.utils import *
# create a hexadecimal random color
def rand_color():
hexadecimal = "#" + ''.join([random.choice('ABCDEF0123456789') for i in range(6)])
return hexadecimal
# assign layer
layer = iface.activeLayer()
# create empty dict to store category:color pairs
colors = {}
# iterate through features and generate random color
# based on category to populate your color dictionary
for feat in layer.getFeatures():
field = feat["code"]
colors[field] = rand_color()
#create new field to store color
pr = layer.dataProvider()
pr.addAttributes([QgsField("Color",QVariant.String, "text", 50)])
layer.updateFields()
# update color field
with edit(layer):
for feat in layer.getFeatures():
feat["Color"] = colors[feat["code"]]
layer.updateFeature(feat)
# create the categorised renderer
categorized_renderer = []
# iterate to assign the color based on the category
for feat in layer.getFeatures():
category = feat["code"]
color = feat["Color"]
categorized_renderer.append(
QgsRendererCategory(category, QgsFillSymbol().createSimple({'color': color}), 'code: {}'.format(category))
)
## apply symbol to layer renderer
renderer = QgsCategorizedSymbolRenderer('code', set(categorized_renderer))
layer.setRenderer(renderer)
# repaint the layer
layer.triggerRepaint()