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.sstatic.net/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

5
  • 1
    there are many undefined variables. the question needs sufficient code for a minimal reproducible example: stackoverflow.com/help/minimal-reproducible-example Commented Jun 7, 2023 at 21:18
  • I tried to update it to include more variables, but I believe the crux of the issue is demonstrated Commented Jun 8, 2023 at 18:57
  • df['Location'] does not exist because a dataframe has not been created. Commented Jun 9, 2023 at 0:27
  • dist_matrix does not exist, what is this ? Commented Jun 9, 2023 at 0: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 ? Commented Jun 9, 2023 at 0:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.