Reputation: 166
I have a dataframe df
with some values from this list ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
, but sometimes not all values appear in df
, for example:
df = pd.DataFrame([['a','b','c'],['b','c','e'],['a', 'e', 'f']])
I plot a heat map-like plot of df
with the code below:
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
import pandas as pd
data = [['a','b','c'],['b','c','e'],['a', 'e', 'f']]
df = pd.DataFrame(data)
value = ['a','b','c', 'd', 'e', 'f', 'g', 'h', 'i','j']
value_to_int = {j:i for i,j in enumerate(value)}
n = len(value_to_int)
#color for value
cmap = ['#b3e6b3', '#66cc66', '#2d862d', '#ffc299','#ff944d', '#ff6600','#ccddff','#99bbff','#4d88ff','#0044cc']
# plot
fig, ax = plt.subplots(figsize = (5, 5))
ax = sns.heatmap(df.replace(value_to_int), cmap=cmap, linewidths = 0.005, annot = False)
#add value into plot
text = df.to_numpy()
for r in range(text.shape[0]):
for c in range(text.shape[1]):
ax.text(c+0.5,r+0.5, text[r,c],
va='center',ha='center')
# modify colorbar:
colorbar = ax.collections[0].colorbar
r = colorbar.vmax - colorbar.vmin
colorbar.set_ticks([colorbar.vmin + r / n * (0.5 + i) for i in range(n)])
colorbar.set_ticklabels(list(value_to_int.keys()))
plt.show()
but the plot I got is not correct, the colors do not fit with the values, for example 'c'
should be dark green, on the heat map is however orange, etc.
how can I modify my code that it show me the correct colors? thank you so much
Upvotes: 0
Views: 653
Reputation: 2020
Short answer: add vmin=0, vmax=9
to the sns.heatmap
call. It has something to do with the scale of the graph and the colorbar.
Upvotes: 1