.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "_examples\indexes\plot_sari_c_relmap.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download__examples_indexes_plot_sari_c_relmap.py>`
        to download the full example code

.. rst-class:: sphx-glr-example-title

.. _sphx_glr__examples_indexes_plot_sari_c_relmap.py:


``SARI`` - By specimen w/ ``sns.relmap``
----------------------------------------

.. todo:: Explain...

.. GENERATED FROM PYTHON SOURCE LINES 8-168



.. rst-class:: sphx-glr-horizontal


    *

      .. image-sg:: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_001.png
         :alt: BLDCUL, Antibiogram (with frequency)
         :srcset: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_001.png
         :class: sphx-glr-multi-img

    *

      .. image-sg:: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_002.png
         :alt: SPTCUL, Antibiogram (with frequency)
         :srcset: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_002.png
         :class: sphx-glr-multi-img

    *

      .. image-sg:: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_003.png
         :alt: URICUL, Antibiogram (with frequency)
         :srcset: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_003.png
         :class: sphx-glr-multi-img

    *

      .. image-sg:: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_004.png
         :alt: WOUCUL, Antibiogram (with frequency)
         :srcset: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_004.png
         :class: sphx-glr-multi-img

    *

      .. image-sg:: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_005.png
         :alt: XINCUL, Antibiogram (with frequency)
         :srcset: /_examples/indexes/images/sphx_glr_plot_sari_c_relmap_005.png
         :class: sphx-glr-multi-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    Data:
           date_received  date_outcome  patient_id laboratory_number specimen_code  specimen_name specimen_description  ... microorganism_name antimicrobial_code antimicrobial_name sensitivity_method  sensitivity mic  reported
    0         2009-01-03           NaN       20091           X428501        BLDCUL            NaN                blood  ...         klebsiella               AAMI           amikacin                NaN    sensitive NaN       NaN
    1         2009-01-03           NaN       20091           X428501        BLDCUL            NaN                blood  ...         klebsiella               AAMO        amoxycillin                NaN    resistant NaN       NaN
    2         2009-01-03           NaN       20091           X428501        BLDCUL            NaN                blood  ...         klebsiella               AAUG          augmentin                NaN    sensitive NaN       NaN
    3         2009-01-03           NaN       20091           X428501        BLDCUL            NaN                blood  ...         klebsiella               AAZT          aztreonam                NaN    sensitive NaN       NaN
    4         2009-01-03           NaN       20091           X428501        BLDCUL            NaN                blood  ...         klebsiella               ACAZ        ceftazidime                NaN    sensitive NaN       NaN
    ...              ...           ...         ...               ...           ...            ...                  ...  ...                ...                ...                ...                ...          ...  ..       ...
    319117    2009-12-31           NaN       24645          H2012337        BLDCUL            NaN                blood  ...       enterococcus               AAMO        amoxycillin                NaN    sensitive NaN       NaN
    319118    2009-12-31           NaN       24645          H2012337        BLDCUL            NaN                blood  ...       enterococcus               ALIN          linezolid                NaN    sensitive NaN       NaN
    319119    2009-12-31           NaN       24645          H2012337        BLDCUL            NaN                blood  ...       enterococcus               ASYN           synercid                NaN    resistant NaN       NaN
    319120    2009-12-31           NaN       24645          H2012337        BLDCUL            NaN                blood  ...       enterococcus               ATEI        teicoplanin                NaN    sensitive NaN       NaN
    319121    2009-12-31           NaN       24645          H2012337        BLDCUL            NaN                blood  ...       enterococcus               AVAN         vancomycin                NaN    sensitive NaN       NaN

    [319122 rows x 15 columns]

    Columns:
    Index(['date_received', 'date_outcome', 'patient_id', 'laboratory_number', 'specimen_code', 'specimen_name', 'specimen_description', 'microorganism_code', 'microorganism_name', 'antimicrobial_code', 'antimicrobial_name', 'sensitivity_method', 'sensitivity', 'mic', 'reported'], dtype='object')
    SARI (overall):
                                                         intermediate  resistant  sensitive    freq    sari
    specimen_code microorganism_code antimicrobial_code                                                    
    BFLCUL        AHS                ACHL                         0.0        0.0        1.0     1.0  0.0000
                                     ACLI                         0.0        0.0        2.0     2.0  0.0000
                                     ACTX                         0.0        0.0        1.0     1.0  0.0000
                                     AERY                         0.0        1.0        1.0     2.0  0.5000
                                     APEN                         0.0        0.0        2.0     2.0  0.0000
    ...                                                           ...        ...        ...     ...     ...
    XINCUL        SAUR               ATEI                         0.0        0.0     1365.0  1365.0  0.0000
                                     ATET                         0.0       67.0     1288.0  1355.0  0.0494
                                     ATRI                         0.0      145.0     1213.0  1358.0  0.1068
                                     AVAN                         0.0        0.0     1364.0  1364.0  0.0000
                  SMAL               ACOT                         0.0        0.0        8.0     8.0  0.0000

    [4491 rows x 5 columns]
    Cultures:
    specimen_code
    URICUL    116627.0
    WOUCUL     94918.0
    XINCUL     21427.0
    SPTCUL     21113.0
    BLDCUL     20333.0
    ENTCUL     13110.0
    T&FCUL      8150.0
    MRSCUL      7865.0
    VAGCUL      7425.0
    EYECUL      2839.0
    GUMCUL      1634.0
    FAECUL      1317.0
    URECUL       802.0
    TISCUL       474.0
    BFLCUL       450.0
    SEMCUL       290.0
    NEOCUL       213.0
    PDFCUL        68.0
    CSFCUL        32.0
    RGNS          20.0
    FUNSTC        14.0
    TBCUL          1.0
    Name: freq, dtype: float64
    C:\Users\kelda\Desktop\repositories\github\pyAMR\main\examples\indexes\plot_sari_c_relmap.py:154: MatplotlibDeprecationWarning:

    The legendHandles attribute was deprecated in Matplotlib 3.7 and will be removed two minor releases later. Use legend_handles instead.

    C:\Users\kelda\Desktop\repositories\github\pyAMR\main\examples\indexes\plot_sari_c_relmap.py:154: MatplotlibDeprecationWarning:

    The legendHandles attribute was deprecated in Matplotlib 3.7 and will be removed two minor releases later. Use legend_handles instead.

    C:\Users\kelda\Desktop\repositories\github\pyAMR\main\examples\indexes\plot_sari_c_relmap.py:154: MatplotlibDeprecationWarning:

    The legendHandles attribute was deprecated in Matplotlib 3.7 and will be removed two minor releases later. Use legend_handles instead.

    C:\Users\kelda\Desktop\repositories\github\pyAMR\main\examples\indexes\plot_sari_c_relmap.py:154: MatplotlibDeprecationWarning:

    The legendHandles attribute was deprecated in Matplotlib 3.7 and will be removed two minor releases later. Use legend_handles instead.

    C:\Users\kelda\Desktop\repositories\github\pyAMR\main\examples\indexes\plot_sari_c_relmap.py:154: MatplotlibDeprecationWarning:

    The legendHandles attribute was deprecated in Matplotlib 3.7 and will be removed two minor releases later. Use legend_handles instead.







|

.. code-block:: default
   :lineno-start: 9


    # Libraries
    import sys
    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib as mpl
    import matplotlib.pyplot as plt

    # Import own libraries
    from pyamr.core.sari import SARI
    from pyamr.core.freq import Frequency
    from pyamr.datasets.load import make_susceptibility

    # -------------------------
    # Configuration
    # -------------------------
    # Configure seaborn style (context=talk)
    sns.set(style="white")

    # Set matplotlib
    mpl.rcParams['xtick.labelsize'] = 9
    mpl.rcParams['ytick.labelsize'] = 9
    mpl.rcParams['axes.titlesize'] = 11
    mpl.rcParams['legend.fontsize'] = 9

    # Pandas configuration
    pd.set_option('display.max_colwidth', 40)
    pd.set_option('display.width', 300)
    pd.set_option('display.precision', 4)

    # Numpy configuration
    np.set_printoptions(precision=2)

    # -------------------------------------------
    # Methods
    # -------------------------------------------
    def create_mapper(dataframe, column_key, column_value):
        """This method constructs a mapper

        Parameters
        ----------
        dataframe: dataframe-like
          The dataframe from which the columns are extracted

        column_key: string-like
          The name of the column with the values for the keys of the mapper

        column_value: string-like
          The name of the column with the values for the values of the mapper

        Returns
        -------
        dictionary
        """
        dataframe = dataframe[[column_key, column_value]]
        dataframe = dataframe.drop_duplicates()
        return dict(zip(dataframe[column_key], dataframe[column_value]))


    # -------------------------------------------
    # Load data
    # -------------------------------------------
    # Load data
    data = make_susceptibility()

    # Show
    print("\nData:")
    print(data)
    print("\nColumns:")
    print(data.columns)

    # -------------------------------------------
    # Compute SARI
    # -------------------------------------------
    # Libraries
    from pyamr.core.sari import SARI

    # Create sari instance
    sari = SARI(groupby=['specimen_code',
                         'microorganism_code',
                         'antimicrobial_code',
                         'sensitivity'])

    # Compute SARI overall
    sari_overall = sari.compute(data,
        return_frequencies=True)

    # Show
    print("SARI (overall):")
    print(sari_overall)


    # -------------------------------------------
    # Plot
    # -------------------------------------------
    # Reset
    sari_overall = sari_overall.reset_index()

    # Count records per specimen
    specimen_count = sari_overall \
        .groupby('specimen_code').freq.sum() \
        .sort_values(ascending=False)

    # Show
    print("Cultures:")
    print(specimen_count)

    # Filter
    sari_overall = sari_overall[sari_overall \
        .specimen_code.isin( \
            specimen_count.index.values[:5])]

    # Loop
    for specimen, df in sari_overall.groupby(by='specimen_code'):

        # ------------
        # Plot Heatmap
        # ------------
        # Create colormap
        cmap = sns.color_palette("Reds", desat=0.5, n_colors=10)

        # Configura
        sizes = (df.freq.min(), df.freq.max())

        # Plot
        g = sns.relplot(data=df.reset_index(), x='microorganism_code',
                        y='antimicrobial_code', hue="sari", size="freq",
                        palette='Reds', hue_norm=(0, 1), edgecolor="gray",
                        linewidth=0.5, sizes=sizes,  # size_norm=sizes,
                        dashes=True, legend='brief', height=10)

        # Configure plot
        g.set(xlabel="Antimicrobial",
              ylabel="Microorganism",
              title='Antibiogram (with frequency)',
              #aspect='equal'
        )
        g.despine(left=True, bottom=True)
        g.ax.margins(.1)

        # Configure xticks
        for label in g.ax.get_xticklabels():
            label.set_rotation(90)

        # Configure legend
        for artist in g.legend.legendHandles:
            artist.set_edgecolor("k")
            artist.set_linewidth(0.5)

        # Superior title
        plt.suptitle(specimen)

        # Add grid lines.
        # plt.grid(linestyle='-', linewidth=0.5, color='.7')

        # Adjust
        plt.tight_layout()

    # Show
    plt.show()

.. rst-class:: sphx-glr-timing

   **Total running time of the script:** ( 0 minutes  5.216 seconds)


.. _sphx_glr_download__examples_indexes_plot_sari_c_relmap.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example




    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: plot_sari_c_relmap.py <plot_sari_c_relmap.py>`

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: plot_sari_c_relmap.ipynb <plot_sari_c_relmap.ipynb>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_