8

I'm making a big dendrogram using SciPy and in the resulting dendrogram the line thickness makes it hard to see detail. I want to decrease the line thickness to make it easier to see and more MatLab like. Any suggestions?

I'm doing:

import scipy.cluster.hierarchy as hicl
from pylab import savefig

distance = #distance matrix

links = hicl.linkage(distance,method='average')
pden = hicl.dendrogram(links,color_threshold=optcutoff[0], ...
       count_sort=True,no_labels=True)
savefig('foo.pdf')

And getting a result like this.

3 Answers 3

17

Matplotlib has a context manager now, which allows you to only override the default values temporarily, for that one plot:

import matplotlib.pyplot as plt
from scipy.cluster import hierarchy

distance = #distance matrix
links = hierarchy.linkage(distance, method='average')

# Temporarily override the default line width:
with plt.rc_context({'lines.linewidth': 0.5}):
    pden = hierarchy.dendrogram(links, color_threshold=optcutoff[0], ...
                                count_sort=True, no_labels=True)
# linewidth is back to its default here...!
plt.savefig('foo.pdf')

See the Matplotlib configuration API for more details.

2
  • 1
    This is amazingly useful in plenty of other contextes! Very neat.
    – Leonard
    Oct 16, 2020 at 11:35
  • This works only for linewidth, other styling options, like linestyle are disabled
    – jarekj71
    Dec 15, 2022 at 13:00
8

Set the default linewidth before calling dendrogram. For example:

import scipy.cluster.hierarchy as hicl
from pylab import savefig
import matplotlib


# Override the default linewidth.
matplotlib.rcParams['lines.linewidth'] = 0.5

distance = #distance matrix

links = hicl.linkage(distance,method='average')
pden = hicl.dendrogram(links,color_threshold=optcutoff[0], ...
       count_sort=True,no_labels=True)
savefig('foo.pdf')

See Customizing matplotlib for more information.

1
  • Can this be done w/o importing matplotlib separately from import pyplot?
    – O.rka
    Sep 28, 2016 at 20:19
0

set dendrogram on existing axes than change its artists using setp. It allow changing all parameters, that won't work if dendrogram is sent to axes or won't work with dendrogram at all like linestyle.

import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as hicl
links = #linkage

fig,ax = plt.subplots()
hicl.dendrogram(links,ax=ax)
plt.setp(ax.collections,linewidth=3,linestyle=":", ...other line parameters...)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.