Python ProgrammingPython Programming

Heatmap with intermediate color text annotations

Create text annotations

import pandas as pd
import matplotlib.pyplot as plt

data = {
        'Basket1': [90, 95, 99, 50, 50, 45, 81],
        'Basket2': [91, 98, 89, 75, 98, 49, 80],
        'Basket3': [92, 97, 99, 85, 96, 75, 88],
        'Basket4': [94, 96, 88, 79, 98, 69, 86]
        }

fig, ax = plt.subplots(figsize=(9, 4))
df = pd.DataFrame.from_dict(data, orient='index')

im = ax.imshow(df.values, cmap="YlGnBu")
fig.colorbar(im)

# Loop over data dimensions and create text annotations
textcolors = ["k", "w"]
threshold = 55
for i in range(len(df)):
    for j in range(len(df.columns)):
        text = ax.text(j, i, df.values[i, j],
                       ha="center", va="center",
                       color=textcolors[df.values[i, j] > threshold])

plt.show()


The following is the output that will be obtained:


Heatmap with intermediate color text annotations in Matplotlib