# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Heatmap

# The `HeatMap` mark represents a 2d matrix of values as a color image. It can be used to visualize a 2d function, or a grayscale image for instance.
#
#
# `HeatMap` is very similar to the `GridHeatMap`, but should be preferred for a greater number of points (starting at around 100x100), to avoid overloading the browser. `GridHeatMap` offers more control (interactions, selections), and is better suited for a smaller number of points.

import numpy as np
from ipywidgets import Layout
import bqplot.pyplot as plt
from bqplot import ColorScale

# ### Data Input
#
# - `x` is a 1d array, corresponding to the abscissas of the points (size N)
# - `y` is a 1d array, corresponding to the ordinates of the points (size M)
# - `color` is a 2d array, $\text{color}_{ij}$ is the intensity of the point $(x_i, y_j)$ (size (N, M))
#
# Scales must be defined for each attribute:
# - a `LinearScale`, `LogScale` or `OrdinalScale` for `x` and `y`
# - a `ColorScale` for `color`

x = np.linspace(-5, 5, 200)
y = np.linspace(-5, 5, 200)
X, Y = np.meshgrid(x, y)
color = np.cos(X ** 2 + Y ** 2)

# ## Plotting a 2-dimensional function
#
# This is a visualization of the function $f(x, y) = \text{cos}(x^2+y^2)$

fig = plt.figure(
    title="Cosine",
    layout=Layout(width="650px", height="650px"),
    min_aspect_ratio=1,
    max_aspect_ratio=1,
    padding_y=0,
)
heatmap = plt.heatmap(color, x=x, y=y)
fig

# ## Displaying an image
#
# The `HeatMap` can be used as is to display a 2d grayscale image, by feeding the matrix of pixel intensities to the `color` attribute

# +
from scipy.misc import ascent

Z = ascent()
Z = Z[::-1, :]
aspect_ratio = Z.shape[1] / Z.shape[0]
# -

img = plt.figure(
    title="Ascent",
    layout=Layout(width="650px", height="650px"),
    min_aspect_ratio=aspect_ratio,
    max_aspect_ratio=aspect_ratio,
    padding_y=0,
)
plt.scales(scales={"color": ColorScale(scheme="Greys", reverse=True)})
axes_options = {
    "x": {"visible": False},
    "y": {"visible": False},
    "color": {"visible": False},
}
ascent = plt.heatmap(Z, axes_options=axes_options)
img

StarcoderdataJupyterScriptsDedupFiltered