Dance Party2
Dance Party2

Reputation: 7536

Seaborn Heatmap Currency Format

Given the following heatmap:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
%matplotlib inline
df = pd.DataFrame(
      {'A' : ['A', 'A', 'B', 'B','C', 'C', 'D', 'D'],
       'B' : ['A', 'B', 'A', 'B','A', 'B', 'A', 'B'],
       'C' : [22000, 4000, 500, 20000, 0, 3000, 90000, 1000],
       'D' : [6000, 62000, 7000, 700, 30000, 30, 1000, 1000]})

df=df.pivot('A','B','C')
fig, ax = plt.subplots(1, 1, figsize =(4,6))

sns.heatmap(df, annot=True, linewidths=0, cbar=False)
plt.show()

I would like the values to display as currency in thousands like this: $22K

Bonus question: Display as thousands with one decimal like this: $8.9K

Upvotes: 1

Views: 2395

Answers (2)

JohanC
JohanC

Reputation: 80309

You can apply a string conversion to each element in the dataframe, and use that for the annotation:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame(
    {'A': ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'],
     'B': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],
     'C': [22000, 4000, 500, 20000, 0, 3000, 90000, 1000],
     'D': [6000, 62000, 7000, 700, 30000, 30, 1000, 1000]})

df = df.pivot('A', 'B', 'C')
df_formatted = df.applymap(
    lambda val: f'${val / 1000:,.0f}K' if round(val / 100) % 10 == 0 else f'${val / 1000:,.1f}K')

fig, ax = plt.subplots(figsize=(4, 6))
sns.heatmap(df, annot=df_formatted, fmt='', linewidths=0, cbar=False, ax=ax)
plt.show()

sns.heatmap with string annotation

Upvotes: 1

Noah
Noah

Reputation: 22646

df["C"] = df["C"].map(lambda x: "${:,.1f}".format(x/1000.))

Upvotes: 1

Related Questions