Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions code/pvclust.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,31 @@ def __init__(self, data, method='ward', metric='euclidean', nboot=1000,
self.result = pd.DataFrame(
[fit(self.r, row, self.nboot) for row in self.bp_by_scale.to_numpy()],
columns=COLUMNS)

def node_positions(self, leaves):
"""(x, y) of each cluster's join in a scipy dendrogram whose leaf
order is ``leaves``, in linkage row order. scipy places the i-th leaf
at x = 5 + 10 i and each join midway between its two branches."""
n_objects = len(leaves)
x = np.empty(2 * n_objects - 1)
x[np.asarray(leaves)] = 5 + 10 * np.arange(n_objects)
for row, (left, right) in enumerate(self.linkage_matrix[:, :2].astype(int)):
x[n_objects + row] = (x[left] + x[right]) / 2
return x[n_objects:], self.linkage_matrix[:, 2]

def plot(self, ax, labels=None, link_color_func=None, fontsize=7):
"""Draw the dendrogram on a matplotlib ``ax`` with AU (red, left) and
BP (green, right) in percent at each join, as pvclust does. Returns
scipy's dendrogram dictionary."""
dend = hierarchy.dendrogram(
self.linkage_matrix, ax=ax, labels=labels, leaf_rotation=90,
color_threshold=0, above_threshold_color='black',
link_color_func=link_color_func)
x, y = self.node_positions(dend['leaves'])
lift = 0.01 * (y.max() if len(y) else 1)
for (au, bp), xi, yi in zip(self.result[['AU', 'BP']].to_numpy(), x, y):
ax.text(xi - 1, yi + lift, f'{round(100 * au)}', color='red',
fontsize=fontsize, ha='right', va='bottom')
ax.text(xi + 1, yi + lift, f'{round(100 * bp)}', color='green',
fontsize=fontsize, ha='left', va='bottom')
return dend
19 changes: 19 additions & 0 deletions code/tests/test_pvclust.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,22 @@ def test_scales_given_in_tenths_are_read_as_fractions():
tenths = pvclust.PvClust(data, nboot=5, r=np.array(range(5, 15)), seed=0)
assert np.allclose(tenths.r, pvclust.PvClust(data, nboot=5, seed=0).r)
assert tenths.n_scaled[0] == 100 and tenths.n_scaled[-1] == 280


def test_plot_labels_every_join_at_its_place_in_the_drawing():
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

data = separated_groups()
pv = pvclust.PvClust(data, nboot=20, seed=0)
fig, ax = plt.subplots()
dend = pv.plot(ax, labels=list(data.columns))
x, y = pv.node_positions(dend['leaves'])
# Each join drawn by scipy is a segment whose top midpoint is (x, y).
drawn = sorted((round((seg_x[1] + seg_x[2]) / 2, 6), round(seg_y[1], 6))
for seg_x, seg_y in zip(dend['icoord'], dend['dcoord']))
assert drawn == sorted(zip(np.round(x, 6), np.round(y, 6)))
texts = [t.get_text() for t in ax.texts]
assert len(texts) == 2 * len(pv.result)
plt.close(fig)
Loading