[
  {
    "path": ".flake8",
    "content": "[flake8]\nignore = E203, E266, E501, W503, F403, F401\nmax-line-length = 79\nmax-complexity = 18\nselect = B,C,E,F,W,T4,B9"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: wcipriano\nbuy_me_a_coffee: wcipriano\n"
  },
  {
    "path": ".gitignore",
    "content": "__pycache__\ndist\n.venv/\n.idea\nbkp/*\n*-local-*\nmatrix-output-*"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n-   repo: https://github.com/ambv/black\n    rev: 20.8b1\n    hooks:\n    - id: black\n-   repo: https://gitlab.com/pycqa/flake8\n    rev: 3.8.4\n    hooks:\n    - id: flake8\n- repo: https://github.com/kynan/nbstripout\n  rev: 0.5.0\n  hooks:\n    - id: nbstripout\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pretty-confusion-matrix?logo=python&logoColor=%23FFFFFF)\n<a href=\"https://pypi.org/project/pretty-confusion-matrix/\"><img alt=\"PyPI\" src=\"https://img.shields.io/pypi/v/pretty-confusion-matrix?logo=pypi&logoColor=%23FFFFFF\"></a>\n<a href=\"https://github.com/psf/black\"><img alt=\"Code style: black\" src=\"https://img.shields.io/badge/code%20style-black-000000.svg?logo=codeclimate&logoColor=%23FFFFFF\"></a>\n![PyPI - Wheel](https://img.shields.io/pypi/wheel/pretty-confusion-matrix)\n<a href=\"https://libraries.io/pypi/pretty-confusion-matrix\"><img alt=\"GitHub Repo stars\" src=\"https://img.shields.io/librariesio/github/wcipriano/pretty-print-confusion-matrix\"></a>\n<a href=\"https://github.com/wcipriano\"><img alt=\"GitHub Repo stars\" src=\"https://img.shields.io/github/license/wcipriano/pretty-print-confusion-matrix?logo=apache\"></a>\n<a href=\"https://github.com/wcipriano/pretty-print-confusion-matrix/blob/master/LICENSE\"><img alt=\"GitHub License\" src=\"https://img.shields.io/github/stars/wcipriano/pretty-print-confusion-matrix?style=flat&logo=github\"></a>\n![PyPI - Downloads](https://img.shields.io/pypi/dm/pretty-confusion-matrix?logo=download)\n\n# Confusion Matrix in Python\nPlot a pretty confusion matrix (like Matlab) in python using seaborn and matplotlib.\n\nThis module get a pretty print confusion matrix from a NumPy matrix or from 2 NumPy arrays (`y_test` and `predictions`).\n\n\n## Become a sponsor\nPlease, consider contributing it to the project.\nSupport the developers who power open source!\nInvest in open source. It powers your world.\nBecome a sponsor now!\n\nIf my open source projects could bring you closer to your goals and you want to say thank you, and you can contribute, feel free to do [Buy me a ☕](https://buymeacoffee.com/wcipriano) !\n\nOr Become a sponsor directly on [GitHub sponsors page](https://github.com/sponsors/wcipriano?frequency=recurring&) ! \nYou will receive a **sponsor badge** on your profile.\n\n\nI will be really thankfull for anything even if it is a coffee or just a kind comment towards my work, because that helps me a lot. \n\nSee my projects and my contacts in my [Linktree](https://linktr.ee/wagner.cipriano) if you want to stay connected!\n\n\n\n\n\n\n## Installation\n```bash\npip install pretty-confusion-matrix\n```\n\n## Get Started\n\n### Plotting from DataFrame:\n```python\nimport numpy as np\nimport pandas as pd\nfrom pretty_confusion_matrix import pp_matrix\n\narray = np.array([[13,  0,  1,  0,  2,  0],\n                  [0, 50,  2,  0, 10,  0],\n                  [0, 13, 16,  0,  0,  3],\n                  [0,  0,  0, 13,  1,  0],\n                  [0, 40,  0,  1, 15,  0],\n                  [0,  0,  0,  0,  0, 20]])\n\n# get pandas dataframe\ndf_cm = pd.DataFrame(array, index=range(1, 7), columns=range(1, 7))\n# colormap: see this and choose your more dear\ncmap = 'PuRd'\npp_matrix(df_cm, cmap=cmap)\n```\n![alt text](https://raw.githubusercontent.com/khuyentran1401/pretty-print-confusion-matrix/master/Screenshots/Conf_matrix_default.png)\n\n\n### Plotting from vectors\n\n\n```python\nimport numpy as np\nfrom pretty_confusion_matrix import pp_matrix_from_data\n\ny_test = np.array([1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2,\n                  3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5])\npredic = np.array([1, 2, 4, 3, 5, 1, 2, 4, 3, 5, 1, 2, 3, 4, 4, 1, 4, 3, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 3, 3, 5, 1, 2, 3, 3, 5, 1, 2,\n                  3, 4, 4, 1, 2, 3, 4, 1, 1, 2, 3, 4, 1, 1, 2, 3, 4, 1, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 4, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5])\n\npp_matrix_from_data(y_test, predic)\n```\n\n![alt text](https://raw.githubusercontent.com/khuyentran1401/pretty-print-confusion-matrix/master/Screenshots/Conf_matrix_default_2.png)\n\n\n## Using custom labels in axis\nYou can customize the labels in axis, whether by DataFrame or vectors.\n\n### From DataFrame\nTo plot the matrix with text labels in axis rather than integer, change the params `index` and `columns` of your dataframe.\nGetting the example one above, just change the line `df_cm = pd.DataFrame(array, index=range(1, 7), columns=range(1, 7))` by\n```python\ncol = ['Dog', 'Cat', 'Mouse', 'Fox', 'Bird', 'Chicken']\ndf_cm = pd.DataFrame(array, index=col, columns=col)\n```\nIt'll replace the integer labels (**1...6**) in the axis, by **Dog, Cat, Mouse**, and so on..\n\n\n### From vectors\nIt's very similar, in this case you just need to use the `columns` param like the example below.\nThis param is a positional array, i.e., the order must be the same of the data representation. \nIn this example _Dog_ will be assigned to the class 0, _Cat_ will be assigned to the class 1, and so on and so forth.\nGetting the example two above, just change the line `pp_matrix_from_data(y_test, predic)`, by\n```python\ncolumns = ['Dog', 'Cat', 'Mouse', 'Fox', 'Bird'] \npp_matrix_from_data(y_test, predic, columns)\n```\nIt'll replace \"class A, ..., class E\" in the axis, by **Dog, Cat, ..., Bird**.\n\nMore information about \"_How to plot confusion matrix with string axis rather than integer in python_\" in [this Stackoverflow answer](https://stackoverflow.com/a/51176855/1809554).\n\n\n\n## Choosing Colormaps\n\nYou can choose the layout of the your matrix by a lot of colors options like PuRd, Oranges and more... \nTo customizer your color scheme, use the param cmap of funcion pp_matrix. \nTo see all the colormap available, please do this:\n```python\nfrom matplotlib import colormaps\nlist(colormaps)\n```\n\nMore information about Choosing Colormaps in Matplotlib is available [here](https://matplotlib.org/stable/users/explain/colors/colormaps.html).\n\n\n\n\n## References:\n### 1. MATLAB confusion matrix:\n\na) [Plot Confusion](https://www.mathworks.com/help/nnet/ref/plotconfusion.html)\n   \nb) [Plot Confusion Matrix Using Categorical Labels](https://www.mathworks.com/help/examples/nnet/win64/PlotConfusionMatrixUsingCategoricalLabelsExample_02.png)\n\n\n\n### 2. Examples and more on Python:\n\n  a) [How to plot confusion matrix with string axis rather than integer in python](https://stackoverflow.com/questions/5821125/how-to-plot-confusion-matrix-with-string-axis-rather-than-integer-in-python/51176855#51176855)\n  \n  b) [Plot-scikit-learn-classification-report](https://stackoverflow.com/questions/28200786/how-to-plot-scikit-learn-classification-report)\n  \n  c) [Plot-confusion-matrix-with-string-axis-rather-than-integer-in-Python](https://stackoverflow.com/questions/5821125/how-to-plot-confusion-matrix-with-string-axis-rather-than-integer-in-python)\n  \n  d) [Seaborn heatmap](https://www.programcreek.com/python/example/96197/seaborn.heatmap)\n  \n  e) [Sklearn-plot-confusion-matrix-with-labels](https://stackoverflow.com/questions/19233771/sklearn-plot-confusion-matrix-with-labels/31720054)\n\n  f) [Model-selection-plot-confusion-matrix](http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py)\n\n"
  },
  {
    "path": "examples/arrays_example.py",
    "content": "import numpy as np\n\nfrom pretty_confusion_matrix import pp_matrix_from_data\n\ny_test = np.array([1, 2, 3, 4, 5])\npredic = np.array([3, 2, 4, 3, 5])\n\ncmap = \"PuRd\"\npath_to_save_img = './matrix-output-from-array.png'\ntitle = 'Confusion matrix from array'\npp_matrix_from_data(y_test, predic, cmap=cmap, path_to_save_img=path_to_save_img, title=title)\n"
  },
  {
    "path": "examples/df_example.py",
    "content": "import numpy as np\nimport pandas as pd\n\nfrom pretty_confusion_matrix import pp_matrix\n\narray = np.array(\n    [\n        [13, 0, 1, 0, 2, 0],\n        [0, 50, 2, 0, 10, 0],\n        [0, 13, 16, 0, 0, 3],\n        [0, 0, 0, 13, 1, 0],\n        [0, 40, 0, 1, 15, 0],\n        [0, 0, 0, 0, 0, 20],\n    ]\n)\n\n# get pandas dataframe\ndf_cm = pd.DataFrame(array, index=range(1, 7), columns=range(1, 7))\n# colormap: see this and choose your more dear\ncmap = \"PuRd\"\ntitle = 'Confusion matrix from dataframe'\npp_matrix(df_cm, cmap=cmap, title=title)\n"
  },
  {
    "path": "examples/docs.py",
    "content": "import pretty_confusion_matrix\n\nprint('VERSION: ', pretty_confusion_matrix.__version__)\n"
  },
  {
    "path": "pretty_confusion_matrix/__init__.py",
    "content": "import importlib.metadata\n__version__ = importlib.metadata.version(\"pretty_confusion_matrix\")\n\nfrom .pretty_confusion_matrix import pp_matrix, pp_matrix_from_data\n"
  },
  {
    "path": "pretty_confusion_matrix/pretty_confusion_matrix.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nplot a pretty confusion matrix with seaborn\nCreated on Mon Jun 25 14:17:37 2018\n@author: Wagner Cipriano - wagnerbhbr - gmail - CEFETMG / MMC\nREFerences:\n  https://www.mathworks.com/help/nnet/ref/plotconfusion.html\n  https://stackoverflow.com/questions/28200786/how-to-plot-scikit-learn-classification-report\n  https://stackoverflow.com/questions/5821125/how-to-plot-confusion-matrix-with-string-axis-rather-than-integer-in-python\n  https://www.programcreek.com/python/example/96197/seaborn.heatmap\n  https://stackoverflow.com/questions/19233771/sklearn-plot-confusion-matrix-with-labels/31720054\n  http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\n\"\"\"\n\nimport matplotlib.font_manager as fm\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sn\nfrom matplotlib.collections import QuadMesh\n\n\ndef get_new_fig(fn, figsize=[9, 9]):\n    \"\"\"Init graphics\"\"\"\n    fig1 = plt.figure(fn, figsize)\n    ax1 = fig1.gca()  # Get Current Axis\n    ax1.cla()  # clear existing plot\n    return fig1, ax1\n\n\ndef configcell_text_and_colors(\n    array_df, lin, col, oText, facecolors, posi, fz, fmt, show_null_values=0\n):\n    \"\"\"\n    config cell text and colors\n    and return text elements to add and to dell\n    @TODO: use fmt\n    \"\"\"\n    text_add = []\n    text_del = []\n    cell_val = array_df[lin][col]\n    tot_all = array_df[-1][-1]\n    per = (float(cell_val) / tot_all) * 100\n    curr_column = array_df[:, col]\n    ccl = len(curr_column)\n\n    # last line  and/or last column\n    if (col == (ccl - 1)) or (lin == (ccl - 1)):\n        # tots and percents\n        if cell_val != 0:\n            if (col == ccl - 1) and (lin == ccl - 1):\n                tot_rig = 0\n                for i in range(array_df.shape[0] - 1):\n                    tot_rig += array_df[i][i]\n                per_ok = (float(tot_rig) / cell_val) * 100\n            elif col == ccl - 1:\n                tot_rig = array_df[lin][lin]\n                per_ok = (float(tot_rig) / cell_val) * 100\n            elif lin == ccl - 1:\n                tot_rig = array_df[col][col]\n                per_ok = (float(tot_rig) / cell_val) * 100\n            per_err = 100 - per_ok\n        else:\n            per_ok = per_err = 0\n\n        per_ok_s = [\"%.2f%%\" % (per_ok), \"100%\"][per_ok == 100]\n\n        # text to DEL\n        text_del.append(oText)\n\n        # text to ADD\n        font_prop = fm.FontProperties(weight=\"bold\", size=fz)\n        text_kwargs = dict(\n            color=\"w\",\n            ha=\"center\",\n            va=\"center\",\n            gid=\"sum\",\n            fontproperties=font_prop,\n        )\n        lis_txt = [\"%d\" % (cell_val), per_ok_s, \"%.2f%%\" % (per_err)]\n        lis_kwa = [text_kwargs]\n        dic = text_kwargs.copy()\n        dic[\"color\"] = \"g\"\n        lis_kwa.append(dic)\n        dic = text_kwargs.copy()\n        dic[\"color\"] = \"r\"\n        lis_kwa.append(dic)\n        lis_pos = [\n            (oText._x, oText._y - 0.3),\n            (oText._x, oText._y),\n            (oText._x, oText._y + 0.3),\n        ]\n        for i in range(len(lis_txt)):\n            newText = dict(\n                x=lis_pos[i][0],\n                y=lis_pos[i][1],\n                text=lis_txt[i],\n                kw=lis_kwa[i],\n            )\n            text_add.append(newText)\n\n        # set background color for sum cells (last line and last column)\n        carr = [0.27, 0.30, 0.27, 1.0]\n        if (col == ccl - 1) and (lin == ccl - 1):\n            carr = [0.17, 0.20, 0.17, 1.0]\n        facecolors[posi] = carr\n\n    else:\n        if per > 0:\n            txt = \"%s\\n%.2f%%\" % (cell_val, per)\n        else:\n            if show_null_values == 0:\n                txt = \"\"\n            elif show_null_values == 1:\n                txt = \"0\"\n            else:\n                txt = \"0\\n0.0%\"\n        oText.set_text(txt)\n\n        # main diagonal\n        if col == lin:\n            # set color of the textin the diagonal to white\n            oText.set_color(\"w\")\n            # set background color in the diagonal to blue\n            facecolors[posi] = [0.35, 0.8, 0.55, 1.0]\n        else:\n            oText.set_color(\"r\")\n\n    return text_add, text_del\n\n\ndef insert_totals(df_cm):\n    \"\"\"insert total column and line (the last ones)\"\"\"\n    sum_col = []\n    for c in df_cm.columns:\n        sum_col.append(df_cm[c].sum())\n    sum_lin = []\n    for item_line in df_cm.iterrows():\n        sum_lin.append(item_line[1].sum())\n    df_cm[\"sum_lin\"] = sum_lin\n    sum_col.append(np.sum(sum_lin))\n    df_cm.loc[\"sum_col\"] = sum_col\n\n\ndef pp_matrix(\n    df_cm,\n    annot=True,\n    cmap=\"Oranges\",\n    fmt=\".2f\",\n    fz=11,\n    lw=0.5,\n    cbar=False,\n    figsize=[8, 8],\n    show_null_values=0,\n    pred_val_axis=\"y\",\n    path_to_save_img=\"\",\n    title=\"Confusion matrix\",\n):\n    \"\"\"\n    print conf matrix with default layout (like matlab)\n    params:\n      df_cm          dataframe (pandas) without totals\n      annot          print text in each cell\n      cmap           Oranges,Oranges_r,YlGnBu,Blues,RdBu, ... see:\n      fz             fontsize\n      lw             linewidth\n      pred_val_axis  where to show the prediction values (x or y axis)\n                      'col' or 'x': show predicted values in columns (x axis) instead lines\n                      'lin' or 'y': show predicted values in lines   (y axis)\n    \"\"\"\n    if pred_val_axis in (\"col\", \"x\"):\n        xlbl = \"Predicted\"\n        ylbl = \"Actual\"\n    else:\n        xlbl = \"Actual\"\n        ylbl = \"Predicted\"\n        df_cm = df_cm.T\n\n    # create \"Total\" column\n    insert_totals(df_cm)\n\n    # this is for print allways in the same window\n    fig, ax1 = get_new_fig(\"Conf matrix default\", figsize)\n\n    ax = sn.heatmap(\n        df_cm,\n        annot=annot,\n        annot_kws={\"size\": fz},\n        linewidths=lw,\n        ax=ax1,\n        cbar=cbar,\n        cmap=cmap,\n        linecolor=\"w\",\n        fmt=fmt,\n    )\n\n    # set ticklabels rotation\n    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, fontsize=10)\n    ax.set_yticklabels(ax.get_yticklabels(), rotation=25, fontsize=10)\n\n    # Turn off all the ticks\n    for (tx, ty) in zip(ax.xaxis.get_major_ticks(), ax.yaxis.get_major_ticks()):\n        tx.tick1line.set_visible(False)\n        tx.tick2line.set_visible(False)\n        ty.tick1line.set_visible(False)\n        ty.tick2line.set_visible(False)\n\n    # face colors list\n    quadmesh = ax.findobj(QuadMesh)[0]\n    facecolors = quadmesh.get_facecolors()\n\n    # iter in text elements\n    array_df = np.array(df_cm.to_records(index=False).tolist())\n    text_add = []\n    text_del = []\n    posi = -1  # from left to right, bottom to top.\n    for t in ax.collections[0].axes.texts:  # ax.texts:\n        pos = np.array(t.get_position()) - [0.5, 0.5]\n        lin = int(pos[1])\n        col = int(pos[0])\n        posi += 1\n\n        # set text\n        txt_res = configcell_text_and_colors(\n            array_df, lin, col, t, facecolors, posi, fz, fmt, show_null_values\n        )\n\n        text_add.extend(txt_res[0])\n        text_del.extend(txt_res[1])\n\n    # remove the old ones\n    for item in text_del:\n        item.remove()\n    # append the new ones\n    for item in text_add:\n        ax.text(item[\"x\"], item[\"y\"], item[\"text\"], **item[\"kw\"])\n\n    # titles and legends\n    ax.set_title(title)\n    ax.set_xlabel(xlbl)\n    ax.set_ylabel(ylbl)\n    plt.tight_layout()  # set layout slim\n\n    # save or show the img result\n    if not path_to_save_img:\n        plt.show()\n    else:\n        plt.savefig(path_to_save_img)\n\n\ndef pp_matrix_from_data(\n    y_test,\n    predictions,\n    columns=None,\n    annot=True,\n    cmap=\"Oranges\",\n    fmt=\".2f\",\n    fz=11,\n    lw=0.5,\n    cbar=False,\n    figsize=[8, 8],\n    show_null_values=0,\n    pred_val_axis=\"lin\",\n    path_to_save_img=\"\",\n    title=\"Confusion matrix\",\n):\n    \"\"\"\n    plot confusion matrix function with y_test (actual values) and predictions (predic),\n    whitout a confusion matrix yet\n    \"\"\"\n    from pandas import DataFrame\n    from sklearn.metrics import confusion_matrix\n\n    # data\n    if not columns:\n        from string import ascii_uppercase\n\n        columns = [\n            \"class %s\" % (i)\n            for i in list(ascii_uppercase)[0 : len(np.unique(y_test))]\n        ]\n\n    confm = confusion_matrix(y_test, predictions)\n    df_cm = DataFrame(confm, index=columns, columns=columns)\n    pp_matrix(\n        df_cm,\n        fz=fz,\n        cmap=cmap,\n        figsize=figsize,\n        show_null_values=show_null_values,\n        pred_val_axis=pred_val_axis,\n        path_to_save_img=path_to_save_img,\n        title=title,\n        annot=annot,\n        fmt=fmt,\n        lw=lw,\n        cbar=cbar\n    )\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.poetry]\nname = \"pretty-confusion-matrix\"\nversion = \"0.6.0\"\ndescription = \"plot a pretty confusion matrix (like Matlab) in python using seaborn and matplotlib\"\nrepository = \"https://github.com/wcipriano/pretty-print-confusion-matrix\"\nauthors = [\"Wagner Cipriano <wagnao@gmail.com>\", \"Khuyen Tran <khuyentran1476@gmail.com>\"]\nkeywords = [\"confusion matrix\"]\nreadme = \"README.md\"\n\n[project.urls]\nhomepage = \"https://pypi.org/project/pretty-confusion-matrix\"\nsource = \"https://github.com/wcipriano/pretty-print-confusion-matrix\"\ndownload = \"https://pypi.org/project/pretty-confusion-matrix/#files\"\ntracker = \"https://github.com/wcipriano/pretty-print-confusion-matrix/issues\"\n\n[tool.poetry.dependencies]\npython = \">=3.9,<3.12\"\nnumpy = [\n    {version = \"^2.0.0\", python = \">=3.9\"},\n]\nmatplotlib = [\n    {version = \"^3.9.0\", python = \">=3.9\"},\n]\nseaborn = \"^0.13.2\"\npandas = [\n    {version = \"^2.2.2\", python = \">=3.9\"},\n]\nscikit-learn = [\n    {version = \"^1.5\", python = \">=3.9\"},\n]\n\n[tool.poetry.dev-dependencies]\npre-commit = \"^3.5.0\"\nblack = \"^24.4.2\"\nflake8 = \"^5.0.4\"\n\n[build-system]\nrequires = [\"poetry-core\"]\nbuild-backend = \"poetry.core.masonry.api\"\n\n[tool.black]\nline-length = 79\ninclude = '\\.pyi?$'\nexclude = '''\n/(\n\t\\.git\n| \\.hg\n| \\.mypy_cache\n| \\.tox\n| \\.venv\n| _build\n| buck-out\n| build   \n)/ \n'''"
  }
]