How do I choose individual colors for contours in matplotlib

Question:

In my short python code below I am plotting risk levels based on values in a csv file and using a shapefile. The code works, but I would like to select specific individual colors for each level, namely green, yellow, orange and red.
Currently it works if I put "Blues", or "Reds" as in the attached png.[image output1.
The line in the code

merged_df.plot(column="risk",colors = ['green','yellow','cyan','red'])

does not work.
How do I specify individual specific colors. help will be appreciated.
The risk data in "Tmaxrisks.csv" is as

"District","risk"
"Berea",1
"Butha Buthe",3
"Leribe",1
"Mafeteng",2
"Maseru",1
"Mohale's Hoek",2
"Mokhotlong",4
"Qacha's Nek",3
"Quthing",3
"Thaba Tseka",4


import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

map_df = gpd.read_file("Shapefiles/BNDA_LSO_1990-01-01_lastupdate/BNDA_LSO_1990-01-01_lastupdate.shx")

risks_df = pd.read_csv("Tmaxrisks.csv")

merged_df = map_df.merge(risks_df, left_on=["adm1nm"], right_on=["District"])

merged_df.plot(column="risk", cmap="Reds", legend=False)
#merged_df.plot(column="risk",colors = ['green','yellow','cyan','red'])

plt.show()
Asked By: Zilore Mumba

||

Answers:

You can map the district to each adm1nm, then the risks to the colors, and pass it to plot :

d = {1: "green", 2: "yellow", 3: "cyan", 4: "red"}

colors = map_df["adm1nm"].map(risks_df.set_index("District")["risk"].map(d))

ax = map_df.plot(color=colors, edgecolor="k", alpha=0.7)

Plot (showing the risks) :

enter image description here

NB: I’m using this dataset to define map_df.

Answered By: Timeless
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.