1
votes

I am trying to plot a shapefile using custom colors on a map using cartopy and matplotlib.

import numpy as np
import matplotlib.pyplot as plt
import cartopy as cartopy
import pandas as pd
import random as rd

def getcolor(buurtnaam):
    a = rd.uniform(0.0, 255.0)
    b = rd.uniform(0.0, 255.0)
    c = rd.uniform(0.0, 255.0)
    return tuple([a, b, c, 1])

ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.set_extent((5.35, 5.60, 51.4, 51.5), crs=cartopy.crs.PlateCarree())
filelocation=('buurt.shp')

reader = cartopy.io.shapereader.Reader(filelocation)

for label,shape in zip(reader.records(),reader.geometries()):
    coordinates=cartopy.feature.ShapelyFeature(shape, cartopy.crs.PlateCarree(),edgecolor='black')
    ax.add_feature(coordinates, facecolor=getcolor(label.attributes['buurtnaam']))
plt.show()

However, this yields the following result:

ValueError: Invalid RGBA argument: 5.850575504984446

When I check my RGBA values by printing them inside the for loop they appear to be correct.

print(label.attributes['buurtnaam'])

Rochusbuurt

print (getcolor(label.attributes['buurtnaam']))

(109.8833008320893, 179.51867989390442, 211.09771601504892, 1)

print (type(getcolor(label.attributes['buurtnaam'])))

class 'tuple'

Is my RGBA formatting correct? Is this a bug in cartopy/matplotlib ?

2

2 Answers

3
votes

In the mean time I solved it. A RGBA tuple should contain 4 values between 0 and 1.

import numpy as np
import matplotlib.pyplot as plt
import cartopy as cartopy
import pandas as pd
import random as rd

def getcolor(buurtnaam):
    a = rd.uniform(0.0, 1.0)
    b = rd.uniform(0.0, 1.0)
    c = rd.uniform(0.0, 1.0)
    return tuple([a, b, c, 1])

ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.set_extent((5.35, 5.60, 51.4, 51.5), crs=cartopy.crs.PlateCarree())
filelocation=('buurt.shp')

reader = cartopy.io.shapereader.Reader(filelocation)

for label,shape in zip(reader.records(),reader.geometries()):
    coordinates=cartopy.feature.ShapelyFeature(shape, cartopy.crs.PlateCarree(),edgecolor='black')
    ax.add_feature(coordinates, facecolor=getcolor(label.attributes['buurtnaam']))
plt.show()
0
votes

It looks like your get_color function is generating random numbers which have nothing to do with your shapefile, and these numbers are being used for your RGB values. When you pass the name of the attribute buurtnaam through to the function, you need to encorporate it in the RGB value generation somehow.