.. 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 <sphx_glr_download__examples_matplotlib_plot_main06_b_heatmap.py>` 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 <div class="output_subarea output_html rendered_html output_result"> <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>AAMI</th> <th>AAMPC</th> <th>AAUG</th> <th>ACAZ</th> <th>ACELX</th> <th>ACIP</th> <th>ACOL</th> </tr> </thead> <tbody> <tr> <th>AAMI</th> <td>1091.0</td> <td>-0.000395</td> <td>0.009905</td> <td>0.006635</td> <td>0.000565</td> <td>0.008569</td> <td>0.002179</td> </tr> <tr> <th>AAMPC</th> <td>5906.0</td> <td>600.000000</td> <td>-0.255642</td> <td>0.070777</td> <td>-0.142713</td> <td>0.101858</td> <td>-0.011118</td> </tr> <tr> <th>AAUG</th> <td>11962.0</td> <td>5942.000000</td> <td>7096.000000</td> <td>-0.027724</td> <td>0.206276</td> <td>0.140313</td> <td>0.027190</td> </tr> <tr> <th>ACAZ</th> <td>11642.0</td> <td>5777.000000</td> <td>11681.000000</td> <td>1052.000000</td> <td>0.455223</td> <td>0.204145</td> <td>-0.011411</td> </tr> <tr> <th>ACELX</th> <td>12005.0</td> <td>5979.000000</td> <td>93618.000000</td> <td>11722.000000</td> <td>7103.000000</td> <td>0.233739</td> <td>-0.013468</td> </tr> <tr> <th>ACIP</th> <td>11992.0</td> <td>5974.000000</td> <td>93507.000000</td> <td>11714.000000</td> <td>93568.000000</td> <td>7115.000000</td> <td>-0.011123</td> </tr> <tr> <th>ACOL</th> <td>9693.0</td> <td>4768.000000</td> <td>9726.000000</td> <td>9526.000000</td> <td>9758.000000</td> <td>9745.000000</td> <td>854.000000</td> </tr> </tbody> </table> </div> </div> <br /> <br /> .. 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 <div class="output_subarea output_html rendered_html output_result"> <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>name</th> <th>category</th> <th>acronym</th> <th>exists_in_registry</th> <th>antimicrobial_code</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>Amikacin</td> <td>Aminoglycosides</td> <td>AMIK</td> <td>True</td> <td>AAMI</td> </tr> <tr> <th>2</th> <td>Amp c markers</td> <td>NaN</td> <td>AMP_C</td> <td>True</td> <td>AAMPC</td> </tr> <tr> <th>5</th> <td>Augmentin</td> <td>NaN</td> <td>AUGM</td> <td>True</td> <td>AAUG</td> </tr> <tr> <th>13</th> <td>Cefotaxime</td> <td>Cephalosporins</td> <td>CEFO</td> <td>True</td> <td>ACTX</td> </tr> <tr> <th>14</th> <td>Cefoxitin</td> <td>Cephalosporins</td> <td>CEFOX</td> <td>True</td> <td>ACXT</td> </tr> <tr> <th>16</th> <td>Ceftazidime</td> <td>Cephalosporins</td> <td>CEFT</td> <td>True</td> <td>ACAZ</td> </tr> <tr> <th>20</th> <td>Cefuroxime</td> <td>Cephalosporins</td> <td>CEFU</td> <td>True</td> <td>ACXM</td> </tr> <tr> <th>21</th> <td>Cephalexin</td> <td>Cephalosporins</td> <td>CEPH</td> <td>True</td> <td>ACELX</td> </tr> <tr> <th>24</th> <td>Ciprofloxacin</td> <td>Fluoroquinolones</td> <td>CIPR</td> <td>True</td> <td>ACIP</td> </tr> <tr> <th>29</th> <td>Colistin sulphate</td> <td>Polypeptides</td> <td>COLI_SULP</td> <td>True</td> <td>ACOL</td> </tr> <tr> <th>35</th> <td>Ertapenem</td> <td>Meropenems</td> <td>ERTA</td> <td>True</td> <td>AERT</td> </tr> <tr> <th>37</th> <td>Esbl markers</td> <td>NaN</td> <td>ESBL_MARK</td> <td>True</td> <td>AESBL</td> </tr> <tr> <th>44</th> <td>Gentamicin</td> <td>Aminoglycosides</td> <td>GENT</td> <td>True</td> <td>AGEN</td> </tr> <tr> <th>45</th> <td>Imipenem</td> <td>Meropenems</td> <td>IMIP</td> <td>True</td> <td>AIMP</td> </tr> <tr> <th>52</th> <td>Mecillinam</td> <td>Penicillins</td> <td>MECI</td> <td>True</td> <td>AMEC</td> </tr> <tr> <th>53</th> <td>Meropenem</td> <td>Meropenems</td> <td>MERO</td> <td>True</td> <td>AMER</td> </tr> <tr> <th>62</th> <td>Nitrofurantoin</td> <td>NaN</td> <td>NITR</td> <td>True</td> <td>ANIT</td> </tr> <tr> <th>81</th> <td>Tazocin</td> <td>NaN</td> <td>TAZO</td> <td>True</td> <td>ATAZ</td> </tr> <tr> <th>83</th> <td>Temocillin</td> <td>Penicillins</td> <td>TEMO</td> <td>True</td> <td>ATEM</td> </tr> <tr> <th>88</th> <td>Tobramycin</td> <td>Aminoglycosides</td> <td>TOBR</td> <td>True</td> <td>ATOB</td> </tr> <tr> <th>89</th> <td>Trimethoprim</td> <td>NaN</td> <td>TRIM</td> <td>True</td> <td>ATRI</td> </tr> </tbody> </table> </div> </div> <br /> <br /> .. 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 <plot_main06_b_heatmap.py>` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_main06_b_heatmap.ipynb <plot_main06_b_heatmap.ipynb>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_