Skip to content
Advertisement

How to plot DENDROGRAM in GUI

I am using a GUI from QtDesigner to plot Dendrogram. My code is below, but I can not plot the Dendrogram, how can I fix it?

Error: 'AxesSubplot' object has no attribute 'dendrogram'
def dendro(self):
    Z = linkage(X, method='ward', metric='euclidean', optimal_ordering=True)
    c, coph_dists = cophenet(Z, pdist(X))
    self.ui.linecoef.setText("%.3f" %c)
    
    fig3 = Figure()
    self.canvas3 = FigureCanvas(fig3)
    self.ui.verticalLayout3.addWidget(self.canvas3)
    fig3.subplots_adjust(top=0.93,bottom=0.125,left=0.1,right=0.97)
    
    ax3f1 = fig3.add_subplot(121)
    ax3f1.dendrogram(Z,leaf_rotation=90., leaf_font_size=8.,)
    ax3f1.set_title('Hierarchical Clustering Dendrogram (full)')
    ax3f1.set_xlabel('sample clusters')
    ax3f1.set_ylabel('distance')
    
    ax3f2 = fig3.add_subplot(122)
    ax3f2.dendrogram(Z,truncate_mode='lastp',  p=12, show_leaf_counts=True, show_contracted=True)
    ax3f2.set_title('Hierarchical Clustering Dendrogram (truncated)')
    ax3f2.set_xlabel('sample clusters size')
    ax3f2.set_ylabel('distance')
    
    self.canvas3.draw()
    

Image of Dendrogram:
Image of Dendrogram

Advertisement

Answer

You have to import the dendrogram from scipy:

from scipy.cluster import hierarchy

And then pass it the axes through the ax argument:

ax3f1 = fig3.add_subplot(121)
hierarchy.dendrogram.dendrogram(
    Z, ax=ax3f2, leaf_rotation=90.0, leaf_font_size=8.0
)
ax3f1.set_title("Hierarchical Clustering Dendrogram (full)")
ax3f1.set_xlabel("sample clusters")
ax3f1.set_ylabel("distance")

ax3f2 = fig3.add_subplot(122)
hierarchy.dendrogram(
    Z,
    ax=ax3f2,
    truncate_mode="lastp",
    p=12,
    show_leaf_counts=True,
    show_contracted=True,
)
ax3f2.set_title("Hierarchical Clustering Dendrogram (truncated)")
ax3f2.set_xlabel("sample clusters size")
ax3f2.set_ylabel("distance")
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement