0

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

  • 1
    there are many undefined variables. the question needs sufficient code for a minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example – D.L Jun 07 '23 at 21:18
  • I tried to update it to include more variables, but I believe the crux of the issue is demonstrated – user22037973 Jun 08 '23 at 18:57
  • `df['Location']` does not exist because a dataframe has not been created. – D.L Jun 09 '23 at 00:27
  • `dist_matrix` does not exist, what is this ? – D.L Jun 09 '23 at 00:28
  • ...if users cannot reproduce the problem then how can they help you, unless the above 2 errors were the problem in the first case ? – D.L Jun 09 '23 at 00:29

0 Answers0