.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/plotting/_imshow.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_plotting__imshow.py: ====================== 6.4 heatmap/imshow ====================== .. GENERATED FROM PYTHON SOURCE LINES 7-19 .. code-block:: default # sphinx_gallery_thumbnail_number = 11 import numpy as np import pandas as pd import matplotlib.pyplot as plt from easy_mpl import imshow from easy_mpl.utils import version_info, despine_axes version_info() # print version information of all the packages being used .. rst-class:: sphx-glr-script-out .. code-block:: none {'easy_mpl': '0.21.4', 'matplotlib': '3.8.4', 'numpy': '1.26.4', 'pandas': '1.5.3', 'scipy': '1.13.1'} .. GENERATED FROM PYTHON SOURCE LINES 20-25 .. code-block:: default x = np.random.random((10, 8)) _ = imshow(x) .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_001.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_001.png, /auto_examples/plotting/images/sphx_glr__imshow_001_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 26-29 .. code-block:: default _ = imshow(x, annotate=True) .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_002.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_002.png, /auto_examples/plotting/images/sphx_glr__imshow_002_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 30-31 show colorbar .. GENERATED FROM PYTHON SOURCE LINES 31-34 .. code-block:: default _ = imshow(x, colorbar=True) .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_003.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_003.png, /auto_examples/plotting/images/sphx_glr__imshow_003_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 35-36 do not show border around colorbar .. GENERATED FROM PYTHON SOURCE LINES 36-39 .. code-block:: default _ = imshow(x, colorbar=True, cbar_params={"border": False}) .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_004.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_004.png, /auto_examples/plotting/images/sphx_glr__imshow_004_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 40-41 Move the colorbar below the heatmap .. GENERATED FROM PYTHON SOURCE LINES 41-45 .. code-block:: default _ = imshow(x, colorbar=True, cbar_params={"border": False, 'pad': 0.4, "orientation":"horizontal"}) .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_005.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_005.png, /auto_examples/plotting/images/sphx_glr__imshow_005_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 46-47 show white grid line .. GENERATED FROM PYTHON SOURCE LINES 47-56 .. code-block:: default data = np.random.random((4, 10)) _ = imshow(data, cmap="YlGn", xticklabels=[f"Feature {i}" for i in range(data.shape[1])], grid_params={'border': True, 'color': 'w', 'linewidth': 2}, annotate=True, colorbar=True) .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_006.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_006.png, /auto_examples/plotting/images/sphx_glr__imshow_006_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 57-60 we can specify color of text in each box of imshow for annotation For this, ``textcolors`` must a numpy array of shape same as that of data. Each value in this numpy array will define color for corresponding box annotation. .. GENERATED FROM PYTHON SOURCE LINES 60-73 .. code-block:: default data = np.arange(9).reshape((3,3)) _ = imshow(data, cmap="Blues", annotate=True, annotate_kws={ "textcolors": np.array([['black', 'black', 'black'], ['black', 'black', 'black'], ['white', 'white', 'white']]), 'fontsize': 14 }, colorbar=True) .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_007.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_007.png, /auto_examples/plotting/images/sphx_glr__imshow_007_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 74-75 We can decide which portion of heatmap to show using ``mask`` argument .. GENERATED FROM PYTHON SOURCE LINES 75-79 .. code-block:: default x = np.random.random((20, 20)) _ = imshow(x, mask=True) .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_008.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_008.png, /auto_examples/plotting/images/sphx_glr__imshow_008_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 80-82 .. code-block:: default _ = imshow(x, mask="upper") .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_009.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_009.png, /auto_examples/plotting/images/sphx_glr__imshow_009_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 83-85 .. code-block:: default _ = imshow(x, mask="lower") .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_010.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_010.png, /auto_examples/plotting/images/sphx_glr__imshow_010_2_0x.png 2.0x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 86-89 The ``imshow`` function returns Axesimage object of matplotlib which can be used for further processing. The Axesimage is not axes, but we can get the axes from Axesimage using Axesimage.axes the process it as shown below. .. GENERATED FROM PYTHON SOURCE LINES 89-136 .. code-block:: default data = pd.read_json('https://climatereanalyzer.org/clim/t2_daily/json_cfsr/cfsr_world_t2_day.json') index = data.pop('name') nyrs = 45 data = pd.DataFrame( np.array([np.array(data.iloc[row, :].values[0]) for row in range(nyrs)]), index=pd.to_datetime(index[0:nyrs]) ) data = data.astype(float) data1 = pd.concat([data.iloc[i, :] for i in range(data.shape[0])]).dropna() data1.index = pd.date_range(data.index[0], periods=len(data1), freq="D") mon_data = data1.resample('M').mean() data_np = np.full(shape=(12, nyrs), fill_value=np.nan) for ii, i in enumerate(range(0, len(mon_data), 12)): data_np[:, ii] = mon_data.iloc[i:i + 12].values print(data_np.shape) im = imshow( data_np, cmap="RdBu_r", aspect="auto", colorbar=True, cbar_params=dict(border=False, title="Mean Temperature", title_kws=dict(fontsize=14)), show=False, ax_kws=dict(xlabel="Years", ylabel="Months", xlabel_kws=dict(fontsize=14), ylabel_kws=dict(fontsize=14)), grid_params={'border': True, 'color': 'w', 'linewidth': 0.5}, ) im.axes.set_yticks(range(12)) im.axes.set_yticklabels( ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']) im.axes.set_xticks(np.linspace(0, data_np.shape[-1], 6)) im.axes.set_xticklabels(np.linspace(data.index.year.min(), data.index.year.max(), 6, dtype=int)) despine_axes(im.axes) im.axes.tick_params(axis=u'y', which=u'both',length=0) ticklabels = [] for ticklabel in im.colorbar.ax.get_yticklabels(): ticklabel.set_text(f"{ticklabel.get_text()}℃") ticklabels.append(ticklabel) im.colorbar.set_ticklabels(ticklabels) plt.tight_layout() plt.show() .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_011.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_011.png, /auto_examples/plotting/images/sphx_glr__imshow_011_2_0x.png 2.0x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none (12, 45) /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/latest/scripts/plotting/_imshow.py:131: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. im.colorbar.set_ticklabels(ticklabels) .. GENERATED FROM PYTHON SOURCE LINES 137-139 We can pass any valid matplotlib cmap. For example, we can use cmaps from seaborn library. .. GENERATED FROM PYTHON SOURCE LINES 139-146 .. code-block:: default import seaborn as sns cm = sns.color_palette("rocket_r", as_cmap=True) print(type(cm)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 147-173 .. code-block:: default im = imshow( data_np, cmap=cm, aspect="auto", colorbar=True, cbar_params=dict(border=False, title="Mean Temperature", title_kws=dict(fontsize=14)), show=False, ax_kws=dict(xlabel="Years", ylabel="Months", xlabel_kws=dict(fontsize=14), ylabel_kws=dict(fontsize=14)), grid_params={'border': True, 'color': 'w', 'linewidth': 0.5}, ) im.axes.set_yticks(range(12)) im.axes.set_yticklabels( ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']) im.axes.set_xticks(np.linspace(0, data_np.shape[-1], 6)) im.axes.set_xticklabels(np.linspace(data.index.year.min(), data.index.year.max(), 6, dtype=int)) despine_axes(im.axes) im.axes.tick_params(axis=u'y', which=u'both',length=0) ticklabels = [] for ticklabel in im.colorbar.ax.get_yticklabels(): ticklabel.set_text(f"{ticklabel.get_text()}℃") ticklabels.append(ticklabel) im.colorbar.set_ticklabels(ticklabels) plt.tight_layout() plt.show() .. image-sg:: /auto_examples/plotting/images/sphx_glr__imshow_012.png :alt: imshow :srcset: /auto_examples/plotting/images/sphx_glr__imshow_012.png, /auto_examples/plotting/images/sphx_glr__imshow_012_2_0x.png 2.0x :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none /home/docs/checkouts/readthedocs.org/user_builds/python-seekho/checkouts/latest/scripts/plotting/_imshow.py:171: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator. im.colorbar.set_ticklabels(ticklabels) .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 5.027 seconds) .. _sphx_glr_download_auto_examples_plotting__imshow.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/AtrCheema/python-seekho/master?urlpath=lab/tree/notebooks/auto_examples/plotting/_imshow.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: _imshow.py <_imshow.py>` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: _imshow.ipynb <_imshow.ipynb>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_