.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "_examples/matplotlib/plot_main06_a_heatmap.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr__examples_matplotlib_plot_main06_a_heatmap.py: 06.a ``sns.heatmap`` for CRI ``v1`` ------------------------------------------- Plot rectangular data as a color-encoded matrix. The generates a heatmap visualization for a dataset related to collateral sensitivity. It uses the Seaborn library to plot the rectangular data as a color-encoded matrix. The code loads the data from a CSV file, creates mappings for categories and colors, and then plots the heatmap using the loaded data and color maps. It also includes annotations, colorbar axes, category patches, legend elements, and formatting options to enhance the visualization. .. GENERATED FROM PYTHON SOURCE LINES 16-42 .. code-block:: default :lineno-start: 16 # Libraries import numpy as np import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt from pathlib import Path from matplotlib.patches import Patch from matplotlib.colors import LogNorm from matplotlib.patches import Rectangle # See https://matplotlib.org/devdocs/users/explain/customizing.html mpl.rcParams['axes.titlesize'] = 8 mpl.rcParams['axes.labelsize'] = 8 mpl.rcParams['xtick.labelsize'] = 8 mpl.rcParams['ytick.labelsize'] = 8 try: __file__ TERMINAL = True except: TERMINAL = False .. GENERATED FROM PYTHON SOURCE LINES 43-44 Lets load the data and create color mapping variables .. GENERATED FROM PYTHON SOURCE LINES 44-64 .. code-block:: default :lineno-start: 45 # Load data path = Path('../../datasets/collateral-sensitivity/sample') data = pd.read_csv(path / 'matrix.csv', index_col=0) abxs = pd.read_csv(path / 'categories.csv', index_col=0) # Create dictionary to map category to color labels = abxs.category palette = sns.color_palette('colorblind', labels.nunique()) palette = sns.cubehelix_palette(labels.nunique(), light=.9, dark=.1, reverse=True, start=1, rot=-2) lookup = dict(zip(labels.unique(), palette)) # Create dictionary to map code to category code2cat = dict(zip(abxs.antimicrobial_code, abxs.category)) # Create colors colors = data.columns.to_series().map(code2cat).map(lookup) .. GENERATED FROM PYTHON SOURCE LINES 65-66 Lets see the data .. GENERATED FROM PYTHON SOURCE LINES 66-71 .. code-block:: default :lineno-start: 66 if TERMINAL: print("\nData:") print(data) data.iloc[:7,:7] .. raw:: html
AAMI AAMPC AAUG ACAZ ACELX ACIP ACOL
AAMI 1091.0 -0.000395 0.009905 0.006635 0.000565 0.008569 0.002179
AAMPC 5906.0 600.000000 -0.255642 0.070777 -0.142713 0.101858 -0.011118
AAUG 11962.0 5942.000000 7096.000000 -0.027724 0.206276 0.140313 0.027190
ACAZ 11642.0 5777.000000 11681.000000 1052.000000 0.455223 0.204145 -0.011411
ACELX 12005.0 5979.000000 93618.000000 11722.000000 7103.000000 0.233739 -0.013468
ACIP 11992.0 5974.000000 93507.000000 11714.000000 93568.000000 7115.000000 -0.011123
ACOL 9693.0 4768.000000 9726.000000 9526.000000 9758.000000 9745.000000 854.000000


.. GENERATED FROM PYTHON SOURCE LINES 72-73 Lets see the antimicrobials .. GENERATED FROM PYTHON SOURCE LINES 73-79 .. code-block:: default :lineno-start: 73 if TERMINAL: print("\nAntimicrobials:") print(abxs) abxs .. raw:: html
name category acronym exists_in_registry antimicrobial_code
0 Amikacin Aminoglycosides AMIK True AAMI
2 Amp c markers NaN AMP_C True AAMPC
5 Augmentin NaN AUGM True AAUG
13 Cefotaxime Cephalosporins CEFO True ACTX
14 Cefoxitin Cephalosporins CEFOX True ACXT
16 Ceftazidime Cephalosporins CEFT True ACAZ
20 Cefuroxime Cephalosporins CEFU True ACXM
21 Cephalexin Cephalosporins CEPH True ACELX
24 Ciprofloxacin Fluoroquinolones CIPR True ACIP
29 Colistin sulphate Polypeptides COLI_SULP True ACOL
35 Ertapenem Meropenems ERTA True AERT
37 Esbl markers NaN ESBL_MARK True AESBL
44 Gentamicin Aminoglycosides GENT True AGEN
45 Imipenem Meropenems IMIP True AIMP
52 Mecillinam Penicillins MECI True AMEC
53 Meropenem Meropenems MERO True AMER
62 Nitrofurantoin NaN NITR True ANIT
81 Tazocin NaN TAZO True ATAZ
83 Temocillin Penicillins TEMO True ATEM
88 Tobramycin Aminoglycosides TOBR True ATOB
89 Trimethoprim NaN TRIM True ATRI


.. GENERATED FROM PYTHON SOURCE LINES 80-81 Lets create some variables. .. GENERATED FROM PYTHON SOURCE LINES 81-91 .. code-block:: default :lineno-start: 82 # Create color maps cmapu = sns.color_palette("YlGn", as_cmap=True) cmapl = sns.diverging_palette(220, 20, as_cmap=True) # Create triangular matrices masku = np.triu(np.ones_like(data)) maskl = np.tril(np.ones_like(data)) .. GENERATED FROM PYTHON SOURCE LINES 92-94 Let's display a heatmap .. GENERATED FROM PYTHON SOURCE LINES 94-165 .. code-block:: default :lineno-start: 95 # Draw (heatmap) fig, axs = plt.subplots(nrows=1, ncols=1, sharey=False, sharex=False, figsize=(8, 5) ) # .. note: This is used to create the colorbar axes. If we want # the default display in which the use the whole fig # height just pass cbar_ax=None. # Create own colorbar axes # Params are [left, bottom, width, height] cbar_ax1 = fig.add_axes([0.76, 0.5, 0.03, 0.38]) cbar_ax2 = fig.add_axes([0.90, 0.5, 0.03, 0.38]) # Display r1 = sns.heatmap(data=data, cmap=cmapu, mask=masku, ax=axs, annot=False, linewidth=0.5, norm=LogNorm(), annot_kws={"size": 8}, square=True, vmin=0, cbar_ax=cbar_ax2, cbar_kws={'label': 'Number of isolates'}) r2 = sns.heatmap(data=data, cmap=cmapl, mask=maskl, ax=axs, annot=False, linewidth=0.5, vmin=-0.7, vmax=0.7, center=0, annot_kws={"size": 8}, square=True, xticklabels=True, yticklabels=True, cbar_ax=cbar_ax1, cbar_kws={'label': 'Collateral Resistance Index'}) # Create patches for categories category_patches = [] for i in axs.get_xticklabels(): try: x, y = i.get_position() c = colors.to_dict().get(i.get_text(), 'k') #i.set_color(c) # for testing # Add patch. category_patches.append( Rectangle((x-0.35, y-0.5), 0.8, 0.3, edgecolor='k', facecolor=c, fill=True, lw=0.25, alpha=0.5, zorder=1000, transform=axs.transData ) ) except Exception as e: print(i.get_text(), e) # Add category rectangles fig.patches.extend(category_patches) # Create legend elements legend_elements = [ Patch(facecolor=v, edgecolor='k', fill=True, lw=0.25, alpha=0.5, label=k) for k, v in lookup.items() ] # Add legend axs.legend(handles=legend_elements, loc='lower left', ncol=1, bbox_to_anchor=(1.1, 0.1), fontsize=8, fancybox=False, shadow=False) # Format plt.suptitle('URINE - Escherichia Coli') #plt.subplots_adjust(left=0.8) plt.tight_layout() # Show plt.show() .. image-sg:: /_examples/matplotlib/images/sphx_glr_plot_main06_a_heatmap_001.png :alt: URINE - Escherichia Coli :srcset: /_examples/matplotlib/images/sphx_glr_plot_main06_a_heatmap_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out Out: .. code-block:: none AMEC Invalid RGBA argument: nan ATEM Invalid RGBA argument: nan /Users/cbit/Desktop/repositories/github/python-spare-code/main/examples/matplotlib/plot_main06_a_heatmap.py:159: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect. .. GENERATED FROM PYTHON SOURCE LINES 166-167 Let's draw a clustermap .. GENERATED FROM PYTHON SOURCE LINES 167-185 .. code-block:: default :lineno-start: 168 """ # Display result = sns.clustermap(data=data, figsize=(6,6), cmap=cmapu, mask=masku, annot=False, linewidth=0.5, norm=LogNorm(), annot_kws={"size": 8}, square=True, vmin=0, row_cluster=False, col_cluster=False, col_colors=colors, xticklabels=True, yticklabels=True) #sns.heatmap(data=data, cmap=cmapl, mask=maskl, ax=result.ax_heatmap, # annot=False, linewidth=0.5, vmin=-0.7, vmax=0.7, # center=0, annot_kws={"size": 8}, square=True, # xticklabels=False, yticklabels=False) # Move the colorbar to the empty space. #result.ax_col_dendrogram.legend(loc="center", ncol=6) #result.cax.set_position([.15, .2, .03, .45]) """ .. rst-class:: sphx-glr-script-out Out: .. code-block:: none '\n# Display\nresult = sns.clustermap(data=data, figsize=(6,6),\n cmap=cmapu, mask=masku, annot=False, linewidth=0.5,\n norm=LogNorm(), annot_kws={"size": 8}, square=True, vmin=0,\n row_cluster=False, col_cluster=False,\n col_colors=colors,\n xticklabels=True, yticklabels=True)\n\n#sns.heatmap(data=data, cmap=cmapl, mask=maskl, ax=result.ax_heatmap,\n# annot=False, linewidth=0.5, vmin=-0.7, vmax=0.7,\n# center=0, annot_kws={"size": 8}, square=True,\n# xticklabels=False, yticklabels=False)\n\n# Move the colorbar to the empty space.\n#result.ax_col_dendrogram.legend(loc="center", ncol=6)\n#result.cax.set_position([.15, .2, .03, .45])\n' .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.539 seconds) .. _sphx_glr_download__examples_matplotlib_plot_main06_a_heatmap.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_main06_a_heatmap.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_main06_a_heatmap.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_