.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "_examples/matplotlib/plot_main06_b_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_b_heatmap.py: 06.b ``sns.heatmap`` for CRI ``v2`` ------------------------------------------- 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-40 .. 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 41-42 Lets load the data and create color mapping variables .. GENERATED FROM PYTHON SOURCE LINES 42-60 .. code-block:: default :lineno-start: 43 # 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()) 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 61-62 Lets see the data .. GENERATED FROM PYTHON SOURCE LINES 62-67 .. code-block:: default :lineno-start: 62 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 68-69 Lets see the antimicrobials .. GENERATED FROM PYTHON SOURCE LINES 69-75 .. code-block:: default :lineno-start: 69 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 76-77 Lets create some variables. .. GENERATED FROM PYTHON SOURCE LINES 77-87 .. code-block:: default :lineno-start: 78 # 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 88-90 Let's display a heatmap .. GENERATED FROM PYTHON SOURCE LINES 90-147 .. code-block:: default :lineno-start: 91 # Draw (heatmap) fig, axs = plt.subplots(nrows=1, ncols=1, sharey=False, sharex=False, figsize=(8, 5) ) # 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_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_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='upper center', ncol=3, bbox_to_anchor=(0.5, -0.25), fontsize=8, fancybox=False, shadow=False) # Format plt.suptitle('URINE - Escherichia Coli') #plt.subplots_adjust(right=0.2) plt.tight_layout() # Show plt.show() .. image-sg:: /_examples/matplotlib/images/sphx_glr_plot_main06_b_heatmap_001.png :alt: URINE - Escherichia Coli :srcset: /_examples/matplotlib/images/sphx_glr_plot_main06_b_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 .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.529 seconds) .. _sphx_glr_download__examples_matplotlib_plot_main06_b_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_b_heatmap.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_main06_b_heatmap.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_