Yes — to display percentages instead of raw counts in your heatmap, you can normalize your crosstab using the normalize argument in pd.crosstab() and then adjust the formatting accordingly.
Here’s how you can modify your code:
pythonCopy codecrosstab = pd.crosstab(
index=df[outcome],
columns=df[meta_var],
normalize='index' # normalize rows to sum to 1
) * 100 # convert proportions to percentages
plt.figure(figsize=(8, 8))
sns.heatmap(crosstab, annot=True, fmt=".1f", cmap="YlGnBu") # show one decimal place
plt.yticks(rotation=0)
plt.title(f'{outcome} taxonomy vs. {meta_var.capitalize()}')
plt.ylabel('Structure')
plt.xlabel(meta_var.capitalize())
plt.tight_layout()
plt.show()
✅ Explanation:
normalize='index': Each row sums to 1 (percentages per outcome).
100: Converts from proportion (0–1) to percentage (0–100).
fmt=".1f": Formats annotations as floating-point numbers (e.g., 32.5).
If instead you want column percentages, use normalize='columns'.
If you want overall percentages, use normalize='all'.
User
How can that be that nothing is ploted when I do that?
Assistant
Good question — that usually means your crosstab ended up empty or full of NaN/zero values after normalization.
Let’s go step by step — there are a few common reasons this happens:
Excellent — that output is exactly what we want 🎯
Your crosstab is not empty, and the normalization worked: the values are between 0 and 1 (fractions).
So the issue isn’t with your data — it’s with how Seaborn’s heatmap interprets your values and your fmt setting.
🔍 The issue
You’re currently using:
pythonCopy codesns.heatmap(crosstab, annot=True, fmt="d", cmap="YlGnBu")
But fmt="d" means “display as integer”.
When you give it floats like 0.041885, it silently fails to render annotations — and depending on your Seaborn/matplotlib version, the entire heatmap can appear blank or all white, because of bad value scaling.
✅ The fix
Change your fmt to a floating-point format, and optionally multiply by 100 if you want percentages:
pythonCopy codeplt.figure(figsize=(10, 8))
sns.heatmap(crosstab * 100, annot=True, fmt=".1f", cmap="YlGnBu")
plt.yticks(rotation=0)
plt.title(f'{outcome} taxonomy vs. {meta_var.capitalize()} (%)')
plt.ylabel('Structure')
plt.xlabel(meta_var.capitalize())
plt.tight_layout()
plt.show()
🧩 1. One of your crosstab variables has missing or constant values
If either df[outcome] or df[meta_var] has NaNs or only one unique value, pd.crosstab() can return an empty DataFrame when normalized.
✅ Check:
pythonCopy codeprint(df[outcome].value_counts(dropna=False))
print(df[meta_var].value_counts(dropna=False))
If you see only one category or a lot of NaNs, that’s the issue.
Fix by dropping missing values:
pythonCopy codedf = df.dropna(subset=[outcome, meta_var])
🧩 2. Normalization resulted in all zeros (e.g. due to integer dtype)
If you don’t multiply by 100 and your dtype is integer, sometimes the division results in zeros that get cast back to int.
✅ Fix:
pythonCopy codecrosstab = pd.crosstab(df[outcome], df[meta_var], normalize='index').astype(float) * 100
🧩 3. The DataFrame is not empty, but the values are tiny or NaN after normalization
Check what’s inside:
pythonCopy codeprint(crosstab)
If you see something like:
lessCopy codeEmpty DataFrame
Columns: []
Index: []
→ means one of the variables had no overlap or was missing.
If you see NaN or very small numbers:
→ try using fillna(0) before plotting:
pythonCopy codecrosstab = crosstab.fillna(0)
🧩 4. The normalization keyword was mis-indented
Make sure you’re actually passing normalize='index' inside pd.crosstab(), not commented out or misplaced.
✅ Full working version to test:
Try this snippet to confirm the plotting logic itself works:
pythonCopy codeimport pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
If this toy example plots fine, then the problem is your actual data, not the code.
If you’d like, paste the output of:
pythonCopy codeprint(df[[outcome, meta_var]].head())
print(pd.crosstab(df[outcome], df[meta_var]))
print(pd.crosstab(df[outcome], df[meta_var], normalize='index'))
and I can pinpoint exactly what’s going wrong.
country_of_birth Russia United Kingdom United States of America
practice_struct
ASCENDING 0.000000 0.000000 0.055556
DESCENDING 0.043478 0.043478 0.000000
MONO_POSITIVE 0.073298 0.010471 0.000000
OSCILLATING 0.061873 0.006689 0.001672
💡 Why this works
fmt=".1f" tells Seaborn to format floats (like 12.5).
Your data already contains valid float values, so you’ll get a proper color gradient.
If you’d like to also show the percentage symbol on the heatmap (e.g. “12.3%”), you can use a custom formatter:
pythonCopy codeimport matplotlib.ticker as mticker
plt.figure(figsize=(10, 8))
ax = sns.heatmap(crosstab * 100, annot=True, fmt=".1f", cmap="YlGnBu")
ax.yaxis.set_tick_params(rotation=0)
ax.xaxis.set_tick_params(rotation=45)
for t in ax.texts:
t.set_text(t.get_text() + " %")
plt.title(f'{outcome} taxonomy vs. {meta_var.capitalize()} (%)')
plt.tight_layout()
plt.show()
✅ In short:
Your data is fine — the heatmap disappeared because fmt="d" can’t display floats.
Switch to fmt=".1f" (and multiply by 100 if you want %) and it’ll plot beautifully.