I have succeeded in changing the color of leaf labels in my dendrogram according to its classification, but I want to follow this coloring upwards.
from scipy.cluster import hierarchy
import matplotlib as plt
#dist_matrix[i,j] is an upper triangle 2d array containing the euclidean distance between each row being compared
linkage_matrix = hierarchy.ward(dist_matrix)
#visualizing dendrogram with basic style elements
hierarchy.dendrogram(linkage_matrix, labels=df.index, leaf_rotation=0, orientation="left", color_threshold=5, above_threshold_color='grey',leaf_font_size=10)
#color codes rows according to column 'Location' in original dataframe
my_palette = plt.colormaps["Accent"]
df['Location']=pd.Categorical(df['Location'])
my_color=df['Location'].cat.codes
ax = plt.pyplot.gca()
xlbls = ax.get_ymajorticklabels()
#sets colors of x-labels according to above coding
num=0
for lbl in xlbls:
val=my_color.iloc[num]
lbl.set_color(my_palette(val))
num+=1
plt.pyplot.figure(figsize=(10,15)) #plots resulting figure
The resulting figure looks like this: https://i.stack.imgur.com/N9axs.png
I have tried reading through the SciPy documentation for the dendrogram, but haven't found a way to achieve this. The same problem was proposed, and recieved a solution, but in R instead of Python: Color dendrogram branches based on external labels uptowards the root until the label matches