{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "#### New to Plotly?\n", "Plotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/).\n", "
You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initialization-for-online-plotting) or [offline](https://plotly.com/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plotly.com/python/getting-started/#start-plotting-online).\n", "
We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!\n", "#### Version Check\n", "Note: Dendrograms are available in version 1.8.7+.\n", "Run `pip install plotly --upgrade` to update your Plotly version." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.4.2'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly\n", "plotly.__version__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Basic Dendrogram" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import numpy as np\n", "\n", "X = np.random.rand(15, 15)\n", "dendro = ff.create_dendrogram(X)\n", "dendro['layout'].update({'width':800, 'height':500})\n", "py.iplot(dendro, filename='simple_dendrogram')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Set Color Threshold" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import numpy as np\n", "\n", "X = np.random.rand(15, 15)\n", "dendro = ff.create_dendrogram(X, color_threshold=1.5)\n", "dendro['layout'].update({'width':800, 'height':500})\n", "py.iplot(dendro, filename='simple_dendrogram_with_color_threshold')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Set Orientation and Add Labels" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.figure_factory as ff\n", "\n", "import numpy as np\n", "\n", "X = np.random.rand(10, 10)\n", "names = ['Jack', 'Oxana', 'John', 'Chelsea', 'Mark', 'Alice', 'Charlie', 'Rob', 'Lisa', 'Lily']\n", "fig = ff.create_dendrogram(X, orientation='left', labels=names)\n", "fig['layout'].update({'width':800, 'height':800})\n", "py.iplot(fig, filename='dendrogram_with_labels')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Plot a Dendrogram with a Heatmap" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import plotly.plotly as py\n", "import plotly.graph_objs as go\n", "import plotly.figure_factory as ff\n", "\n", "import numpy as np\n", "from scipy.spatial.distance import pdist, squareform\n", "\n", "\n", "# get data\n", "data = np.genfromtxt(\"http://files.figshare.com/2133304/ExpRawData_E_TABM_84_A_AFFY_44.tab\",\n", " names=True,usecols=tuple(range(1,30)),dtype=float, delimiter=\"\\t\")\n", "data_array = data.view((np.float, len(data.dtype.names)))\n", "data_array = data_array.transpose()\n", "labels = data.dtype.names\n", "\n", "# Initialize figure by creating upper dendrogram\n", "figure = ff.create_dendrogram(data_array, orientation='bottom', labels=labels)\n", "for i in range(len(figure['data'])):\n", " figure['data'][i]['yaxis'] = 'y2'\n", "\n", "# Create Side Dendrogram\n", "dendro_side = ff.create_dendrogram(data_array, orientation='right')\n", "for i in range(len(dendro_side['data'])):\n", " dendro_side['data'][i]['xaxis'] = 'x2'\n", "\n", "# Add Side Dendrogram Data to Figure\n", "for data in dendro_side['data']:\n", " figure.add_trace(data)\n", "\n", "# Create Heatmap\n", "dendro_leaves = dendro_side['layout']['yaxis']['ticktext']\n", "dendro_leaves = list(map(int, dendro_leaves))\n", "data_dist = pdist(data_array)\n", "heat_data = squareform(data_dist)\n", "heat_data = heat_data[dendro_leaves,:]\n", "heat_data = heat_data[:,dendro_leaves]\n", "\n", "heatmap = [\n", " go.Heatmap(\n", " x = dendro_leaves, \n", " y = dendro_leaves,\n", " z = heat_data, \n", " colorscale = 'Blues'\n", " )\n", "]\n", "\n", "heatmap[0]['x'] = figure['layout']['xaxis']['tickvals']\n", "heatmap[0]['y'] = dendro_side['layout']['yaxis']['tickvals']\n", "\n", "# Add Heatmap Data to Figure\n", "for data in heatmap:\n", " figure.add_trace(data)\n", "\n", "# Edit Layout\n", "figure['layout'].update({'width':800, 'height':800,\n", " 'showlegend':False, 'hovermode': 'closest',\n", " })\n", "# Edit xaxis\n", "figure['layout']['xaxis'].update({'domain': [.15, 1],\n", " 'mirror': False,\n", " 'showgrid': False,\n", " 'showline': False,\n", " 'zeroline': False,\n", " 'ticks':\"\"})\n", "# Edit xaxis2\n", "figure['layout'].update({'xaxis2': {'domain': [0, .15],\n", " 'mirror': False,\n", " 'showgrid': False,\n", " 'showline': False,\n", " 'zeroline': False,\n", " 'showticklabels': False,\n", " 'ticks':\"\"}})\n", "\n", "# Edit yaxis\n", "figure['layout']['yaxis'].update({'domain': [0, .85],\n", " 'mirror': False,\n", " 'showgrid': False,\n", " 'showline': False,\n", " 'zeroline': False,\n", " 'showticklabels': False,\n", " 'ticks': \"\"})\n", "# Edit yaxis2\n", "figure['layout'].update({'yaxis2':{'domain':[.825, .975],\n", " 'mirror': False,\n", " 'showgrid': False,\n", " 'showline': False,\n", " 'zeroline': False,\n", " 'showticklabels': False,\n", " 'ticks':\"\"}})\n", "\n", "# Plot!\n", "py.iplot(figure, filename='dendrogram_with_heatmap')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "layout.XAxis({\n", " 'mirror': 'allticks',\n", " 'rangemode': 'tozero',\n", " 'showgrid': False,\n", " 'showline': True,\n", " 'showticklabels': True,\n", " 'ticks': 'outside',\n", " 'type': 'linear',\n", " 'zeroline': False\n", "})" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dendro_side['layout']['xaxis']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reference" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function create_dendrogram in module plotly.figure_factory._dendrogram:\n", "\n", "create_dendrogram(X, orientation='bottom', labels=None, colorscale=None, distfun=None, linkagefun= at 0x000001C336B28048>, hovertext=None, color_threshold=None)\n", " BETA function that returns a dendrogram Plotly figure object.\n", " \n", " :param (ndarray) X: Matrix of observations as array of arrays\n", " :param (str) orientation: 'top', 'right', 'bottom', or 'left'\n", " :param (list) labels: List of axis category labels(observation labels)\n", " :param (list) colorscale: Optional colorscale for dendrogram tree\n", " :param (function) distfun: Function to compute the pairwise distance from\n", " the observations\n", " :param (function) linkagefun: Function to compute the linkage matrix from\n", " the pairwise distances\n", " :param (list[list]) hovertext: List of hovertext for constituent traces of dendrogram\n", " clusters\n", " :param (double) color_threshold: Value at which the separation of clusters will be made\n", " \n", " Example 1: Simple bottom oriented dendrogram\n", " ```\n", " import plotly.plotly as py\n", " from plotly.figure_factory import create_dendrogram\n", " \n", " import numpy as np\n", " \n", " X = np.random.rand(10,10)\n", " dendro = create_dendrogram(X)\n", " plot_url = py.plot(dendro, filename='simple-dendrogram')\n", " \n", " ```\n", " \n", " Example 2: Dendrogram to put on the left of the heatmap\n", " ```\n", " import plotly.plotly as py\n", " from plotly.figure_factory import create_dendrogram\n", " \n", " import numpy as np\n", " \n", " X = np.random.rand(5,5)\n", " names = ['Jack', 'Oxana', 'John', 'Chelsea', 'Mark']\n", " dendro = create_dendrogram(X, orientation='right', labels=names)\n", " dendro['layout'].update({'width':700, 'height':500})\n", " \n", " py.iplot(dendro, filename='vertical-dendrogram')\n", " ```\n", " \n", " Example 3: Dendrogram with Pandas\n", " ```\n", " import plotly.plotly as py\n", " from plotly.figure_factory import create_dendrogram\n", " \n", " import numpy as np\n", " import pandas as pd\n", " \n", " Index= ['A','B','C','D','E','F','G','H','I','J']\n", " df = pd.DataFrame(abs(np.random.randn(10, 10)), index=Index)\n", " fig = create_dendrogram(df, labels=Index)\n", " url = py.plot(fig, filename='pandas-dendrogram')\n", " ```\n", "\n" ] } ], "source": [ "help(ff.create_dendrogram)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Collecting git+https://github.com/plotly/publisher.git\n", " Cloning https://github.com/plotly/publisher.git to c:\\users\\thars\\appdata\\local\\temp\\pip-req-build-p1ivo3bg\n", "Building wheels for collected packages: publisher\n", " Running setup.py bdist_wheel for publisher: started\n", " Running setup.py bdist_wheel for publisher: finished with status 'done'\n", " Stored in directory: C:\\Users\\thars\\AppData\\Local\\Temp\\pip-ephem-wheel-cache-jom4cebv\\wheels\\99\\3e\\a0\\fbd22ba24cca72bdbaba53dbc23c1768755fb17b3af0f33966\n", "Successfully built publisher\n", "Installing collected packages: publisher\n", " Found existing installation: publisher 0.13\n", " Uninstalling publisher-0.13:\n", " Successfully uninstalled publisher-0.13\n", "Successfully installed publisher-0.13\n" ] } ], "source": [ "from IPython.display import display, HTML\n", "\n", "display(HTML(''))\n", "display(HTML(''))\n", "\n", "! pip install git+https://github.com/plotly/publisher.git --upgrade\n", "import publisher\n", "publisher.publish(\n", " 'dendrograms.ipynb', 'python/dendrogram/', 'Python Dendrograms',\n", " 'How to make a dendrogram in Python with Plotly. ',\n", " name = 'Dendrograms',\n", " title = \"Dendrograms | Plotly\",\n", " thumbnail='thumbnail/dendrogram.jpg', language='python',\n", " has_thumbnail='true', display_as='scientific', order=6,\n", " ipynb= '~notebook_demo/262')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 1 }