Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Dendrogram andrew tweaks #312

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
theengineear merged 38 commits into master from dendrogram-andrew-tweaks
Oct 2, 2015
Merged
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
3d6dbb9
Added Dendrogram class and tests
merenlin Jul 28, 2015
2d9b88c
Added a small validator
merenlin Aug 4, 2015
819e41e
updates after renaming
merenlin Aug 4, 2015
3781906
Moved dendrogram tests to optional
merenlin Aug 12, 2015
31efa33
Protected scipy imports
merenlin Aug 12, 2015
02beb6c
Fixed typos, docstring and return value
merenlin Aug 12, 2015
bfd3cca
Typo
merenlin Aug 12, 2015
ff98cb7
Fixing default colors mapping
merenlin Aug 15, 2015
4afc8c9
Minor styling changes and fixes
merenlin Aug 15, 2015
57e15bd
pep8 and docsrings
merenlin Aug 15, 2015
b7d3d31
pep8 in tests
merenlin Aug 15, 2015
44cdece
Styling and imports
merenlin Aug 28, 2015
16c74c1
Cleanup of labels, axis and tests
merenlin Sep 1, 2015
ebff53e
Added more tests and fixed axis reference
merenlin Sep 1, 2015
0de0349
another fix for axis confusion
merenlin Sep 1, 2015
20fc40c
Added colorscale test
merenlin Sep 4, 2015
88842b1
cow comments
merenlin Sep 4, 2015
b9352d7
Merge branch 'master' into dendrogram-andrew-tweaks
theengineear Sep 30, 2015
e7bf58c
Duplicate `width` to `height` in layout update.
theengineear Sep 30, 2015
3632084
Make docs a little bit more consistent.
theengineear Sep 30, 2015
8aea12e
Spell check.
theengineear Sep 30, 2015
fae2047
pep:8ball:
theengineear Sep 30, 2015
723dde4
pep:8ball:
theengineear Sep 30, 2015
806a6e0
`autoscale` —> `autosize`
theengineear Sep 30, 2015
ca08777
Add a `NumpyTestUtilsMixin` to help dict comps.
theengineear Sep 30, 2015
8866e34
Show that the dendrogram test should have failed!
theengineear Sep 30, 2015
d0b0f6a
Fix dendrogram test, lock down *entire* figure.
theengineear Sep 30, 2015
fc7ce40
Merge branch 'dendrogram-andrew-tweaks' of https://github.com/plotly/...
theengineear Sep 30, 2015
bed3bec
Lock down `test_dendrogram_random_matrix` test.
theengineear Sep 30, 2015
f3b57fc
Fix duplicated `test_dendrogram_orientation` test.
theengineear Sep 30, 2015
3cf13ae
Lock down `test_dendrogram_orientation_two` spec.
theengineear Sep 30, 2015
dab5d37
Rename `.._orientation_two` —> `.._colorscale`.
theengineear Sep 30, 2015
89592cd
PY3 fix. Can’t index a `.keys()` view.
theengineear Sep 30, 2015
3e3de24
Loosen `dtype` on constructor in test. (PY3 fail).
theengineear Sep 30, 2015
76361e6
Rename test suite for figure factory.
theengineear Sep 30, 2015
85dccd1
Merge branch 'master' into dendrogram-andrew-tweaks
theengineear Oct 1, 2015
01d2826
For consistency use Fixed and Added in changelog.
theengineear Oct 1, 2015
3815a8f
version bump —> 1.8.7 (added dendrogram)
theengineear Oct 1, 2015
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
Prev Previous commit
Next Next commit
pep8 and docsrings
  • Loading branch information
merenlin committed Aug 15, 2015
commit 57e15bdffbd5f4ffd00d0e349e8346116ab4ee56
143 changes: 91 additions & 52 deletions plotly/tools.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2285,9 +2285,15 @@ def create_candlestick(open, high, low, close,

@staticmethod
def create_dendrogram(X, orientation="bottom", labels=None,
colorscale=None, **kwargs):
colorscale=None):
"""
Returns a dendrogram Plotly figure object.
BETA function that returns a dendrogram Plotly figure object.

:param (ndarray) X: Matrix of observations as arrray of arrays
:param (str) orientation: 'top', 'right', 'bottom', or 'left'
:param (list) labels: List of axis category labels(observation labels)
:param (list) colorscale: Optional colorscale for dendrogram tree
clusters

X: Heatmap matrix as array of arrays
orientation: 'top', 'right', 'bottom', or 'left'
Expand All @@ -2302,7 +2308,7 @@ def create_dendrogram(X, orientation="bottom", labels=None,

import numpy as np

X = np.random.rand(5,5)
X = np.random.rand(5,5)
dendro_X = FF.create_dendrogram(X)
py.iplot(dendro_X, validate=False, height=300, width=1000)

Expand All @@ -2319,15 +2325,19 @@ def create_dendrogram(X, orientation="bottom", labels=None,
"""

if _scipy_imported is False:
raise ImportError("FigureFactory.create_dendrogram requires scipy, scipy.spatial and scipy.hierarchy")
raise ImportError("FigureFactory.create_dendrogram requires scipy,
scipy.spatial and scipy.hierarchy")

s = X.shape
if len(s) != 2:
exceptions.PlotlyError("X should be 2-dimensional array.")

dendrogram = _Dendrogram(X, orientation, labels, colorscale)

return {'layout': dendrogram.layout, 'data': dendrogram.data, 'labels': dendrogram.labels}
return {'layout': dendrogram.layout,
'data': dendrogram.data,
'labels': dendrogram.labels}


class _Quiver(FigureFactory):
"""
Expand Down Expand Up @@ -2925,34 +2935,34 @@ def get_candle_decrease(self):
stick_decrease_y, stick_decrease_x)

class _Dendrogram(FigureFactory):
''' Returns a Dendrogram figure object
Example usage:
D = Dendrogram( Z )
fig = { 'data':D.data, 'layout':D.layout }
py.iplot( fig, filename='Dendro', validate=False )'''

"""
Refer to FigureFactory.create_dendrogram() for docstring.
"""

def __init__(self, X, orientation='bottom', labels=None, colorscale=None, \
width="100%", height="100%", xaxis='xaxis', yaxis='yaxis' ):
''' Draw a 2d dendrogram tree
X: Heatmap matrix as array of arrays
orientation: 'top', 'right', 'bottom', or 'left'
labels: List of axis category labels
colorscale: Optional colorscale for dendrogram tree clusters
Returns a dendrogram Plotly figure object '''

self.orientation = orientation
self.labels = labels
self.xaxis = xaxis
self.yaxis = yaxis
self.data = []
self.leaves = []
self.sign = { self.xaxis:1, self.yaxis:1 }
self.layout = { self.xaxis:{}, self.yaxis:{} }

self.sign[self.xaxis] = 1 if self.orientation in ['left','bottom'] else -1
self.sign[self.yaxis] = 1 if self.orientation in ['right','bottom'] else -1
self.sign = {self.xaxis: 1, self.yaxis: 1}
self.layout = {self.xaxis: {}, self.yaxis: {}}

if self.orientation in ['left', 'bottom']:
self.sign[self.xaxis] = 1
else:
self.sign[self.xaxis] = -1

if self.orientation in ['right', 'bottom']:
self.sign[self.yaxis] = 1
else:
self.sign[self.yaxis] = -1

dd_traces, xvals, yvals, ordered_labels, leaves = self.get_dendrogram_traces( X, colorscale )
dd_traces, xvals, yvals,
ordered_labels, leaves = self.get_dendrogram_traces(X, colorscale)

self.labels = ordered_labels
self.leaves = leaves
Expand All @@ -2971,7 +2981,11 @@ def __init__(self, X, orientation='bottom', labels=None, colorscale=None, \
self.data = Data(dd_traces)

def get_color_dict(self, colorscale):
''' Return colorscale used for dendrogram tree clusters '''
"""
Returns colorscale used for dendrogram tree clusters
:param (list) colorscale: colors to use for the plot,
in rgb format
"""

# These are the color codes returned for dendrograms
# We're replacing them with nicer colors
Expand Down Expand Up @@ -3004,9 +3018,11 @@ def get_color_dict(self, colorscale):
return default_colors

def set_axis_layout(self, axis_key):
''' Sets and returns default axis object for dendrogram figure
axis_key: "xaxis", "xaxis1", "yaxis", yaxis1", etc '''

"""
Sets and returns default axis object for dendrogram figure
:param (str) axis_key: "xaxis", "xaxis1", "yaxis", yaxis1", etc.
"""

axis_defaults = {
'type': 'linear',
'ticks': 'outside',
Expand All @@ -3024,7 +3040,8 @@ def set_axis_layout(self, axis_key):
axis_key_labels = self.yaxis
if axis_key_labels not in self.layout:
self.layout[axis_key_labels] = {}
self.layout[axis_key_labels]['tickvals'] = [ea*self.sign[axis_key] for ea in self.zero_vals]
self.layout[axis_key_labels]['tickvals'] = [ea*self.sign[axis_key]
for ea in self.zero_vals]
self.layout[axis_key_labels]['ticktext'] = self.labels
self.layout[axis_key_labels]['tickmode'] = 'array'

Expand All @@ -3033,11 +3050,13 @@ def set_axis_layout(self, axis_key):
return self.layout[axis_key]

def set_figure_layout(self, width, height):
''' Sets and returns default layout object for dendrogram figure '''
"""
Sets and returns default layout object for dendrogram figure
"""

self.layout.update({
'showlegend': False,
'autoscale': False,
'autoscale': False,
'hovermode': 'closest',
'width': width,
'width': height
Expand All @@ -3048,35 +3067,55 @@ def set_figure_layout(self, width, height):

return self.layout

def get_dendrogram_traces( self, X, colorscale ):
''' Returns a tuple with:
(a) List of Plotly trace objects for the dendrogram tree
(b) icoord: All X points of the dendogram tree as array of arrays with length 4
(c) dcoord: All Y points of the dendogram tree as array of arrays with length 4 '''
def get_dendrogram_traces(self, X, colorscale):
"""
Calculates all the elements needed for plotting a dendrogram

:rtype (tuple): Contains all the traces in the following order
(a) trace_list: List of Plotly trace objects for the dendrogram
tree
(b) icoord: All X points of the dendogram tree as array of arrays
with length 4
(c) dcoord: All Y points of the dendogram tree as array of arrays
with length 4
(d) ordered_labels: leaf labels in the order they are going to
appear on the plot
(e) P['leaves']: left-to-right traversal of the leaves
"""

d = scs.distance.pdist(X)
Z = sch.linkage(d, method='complete')
P = sch.dendrogram(Z, orientation=self.orientation,labels=self.labels, no_plot=True)

icoord = scp.array( P['icoord'] )
dcoord = scp.array( P['dcoord'] )
ordered_labels = scp.array( P['ivl'] )
color_list = scp.array( P['color_list'] )
colors = self.get_color_dict( colorscale )
Z = sch.linkage(d, method='complete')
P = sch.dendrogram(Z, orientation=self.orientation,
labels=self.labels, no_plot=True)

icoord = scp.array(P['icoord'])
dcoord = scp.array(P['dcoord'])
ordered_labels = scp.array(P['ivl'])
color_list = scp.array(P['color_list'])
colors = self.get_color_dict(colorscale)

trace_list = []

for i in range(len(icoord)):
# xs and ys are arrays of 4 points that make up the '∩' shapes of the dendrogram tree
xs = icoord[i] if self.orientation in ['top','bottom'] else dcoord[i]
ys = dcoord[i] if self.orientation in ['top','bottom'] else icoord[i]
color_key = color_list[i]
trace = Scatter(x=np.multiply(self.sign[self.xaxis],xs), \
y=np.multiply(self.sign[self.yaxis],ys), \
mode='lines', marker=Marker(color=colors[color_key]) )
# xs and ys are arrays of 4 points that make up the '∩' shapes
# of the dendrogram tree
if self.orientation in ['top', 'bottom']:
xs = icoord[i]
else:
xs = dcoord[i]

if self.orientation in ['top', 'bottom']:
ys = dcoord[i]
else:
ys = icoord[i]
color_key = color_list[i]
trace = Scatter(x=np.multiply(self.sign[self.xaxis], xs),
y=np.multiply(self.sign[self.yaxis], ys),
mode='lines',
marker=Marker(color=colors[color_key]))
trace['xaxis'] = 'x'+self.xaxis[-1]
trace['yaxis'] = 'y'+self.yaxis[-1]
trace_list.append(trace)
trace_list.append(trace)

return trace_list, icoord, dcoord, ordered_labels, P['leaves']

AltStyle によって変換されたページ (->オリジナル) /