'How can I create an automated line that cut a dendrogram based on cluster number?

I'm coding in python, trying to create an horizontal line based on decided number of clusters. In my case I used 5 number of clusters, and the distance (according to dendrogram) is ~70 .

I'm using mall customer dataset 2

This is my code

import scipy.cluster.hierarchy as sch
dendrogram = sch.dendrogram(sch.linkage(X, method = Method), truncate_mode = 'lastp', p=100)

plt.rcParams['figure.figsize'] = (20,10)
plt.axhline(y=70, c='grey', lw=1, linestyle='dashed')#Here the "70" should be a variable I don't see how I can get
plt.title('Dendogram  (Truncated)')
plt.xlabel('Observations')[enter image description here]
plt.ylabel(' Euclidian Distances')
plt.show()

1

My main question is : How can I get that line given a decided number of clusters? , Is there a function to get the number on ax Y (distances) from dendrogram?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source