Issue
I have a dataframe df
with values from 0 to x (x is integer and no fixed value), in my example is x=10
I want to map the heatmap with cmap 'Reds', however where value 0 is should not be white but green '#009933'
import seaborn as sns # matplotlib inline
import random
data = []
for i in range(10):
data.append([random.randrange(0, 11, 1) for _ in range(10)])
df = pd.DataFrame(data)
fig, ax = plt.subplots(figsize = (12, 10))
# cmap = [????]
ax = sns.heatmap(df, cmap='Reds', linewidths = 0.005, annot = True, cbar=True)
plt.show()
Solution
You can use a LinearSegmentedColormap
from matplotlib.colors
. You first have to find the largest value, in this case 10, then use that to create a colors variable that starts with green, then goes to the standard 'Reds' colorset. Also, set the colorbar to False when making the heatmap with seaborn, and separately make one with matplotlib.
This code was adapted from here:
import matplotlib.pyplot as plt
import matplotlib.colors as cl
import seaborn as sns
import pandas as pd
import numpy as np
import random
data = []
for i in range(10):
data.append([random.randrange(0, 11, 1) for _ in range(10)])
df = pd.DataFrame(data)
fig, ax = plt.subplots(figsize = (12, 10))
cmap_reds = plt.get_cmap('Reds')
num_colors = 11
colors = ['#009933'] + [cmap_reds(i / num_colors) for i in range(1, num_colors)]
cmap = cl.LinearSegmentedColormap.from_list('', colors, num_colors)
ax = sns.heatmap(df, cmap=cmap, vmin=0, vmax=num_colors, square=True, cbar=False, annot = True)
cbar = plt.colorbar(ax.collections[0], ticks=range(num_colors + 1))
cbar.set_ticks(np.linspace(0, num_colors, 2*num_colors+1)[1::2])
cbar.ax.set_yticklabels(range(num_colors))
plt.show()
Answered By - DapperDuck
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.