Home > OS >  Setting xtick labels in of an sns.heatmap subplot
Setting xtick labels in of an sns.heatmap subplot

Time:01-18

I am trying to put 3 subplots of sns.heatmap with custom xticklabels and yticklabels. You can see that the labels I enter overlaps with some default labels. How to avoid this?

glue = sns.load_dataset("glue").pivot("Model", "Task", "Score")
xlabels=['a','b','c','d','e','f','g','h']
ylabels=['AA','BB','CC','DD','EE','FF','GG','HH']

fig, (ax1,ax2,ax3) = plt.subplots(nrows=1, ncols=3,figsize=(24,8))
ax1 = fig.add_subplot(1,3,1)
# figure(figsize=(6, 4), dpi=80)
ax1=sns.heatmap(glue, annot=True,cmap='Reds', cbar=False, linewidths=0.2, linecolor='white',xticklabels=xlabels, yticklabels=ylabels)

xlabels=['p','q','r','s','t','u','v','z']
ylabels=['PP','QQ','RR','SS','TT','UU','VV','ZZ']
ax2 = fig.add_subplot(1,3,2)
ax2=sns.heatmap(glue, annot=True,cmap='Blues', cbar=False, linewidths=0.2, linecolor='white',xticklabels=xlabels, yticklabels=ylabels)

xlabels=['10','20','30','40','50','60','70','80']
ylabels=['11','21','31','41','51','61','71','81']
ax3 = fig.add_subplot(1,3,3)
ax3=sns.heatmap(glue, annot=True,cmap='Greens', cbar=False, linewidths=0.2, linecolor='white',xticklabels=xlabels, yticklabels=ylabels)

enter image description here

CodePudding user response:

No need to add_subplot, since you've already created the subplots with plt.subplots. Use the ax parameter of heatmap:

fig, (ax1,ax2,ax3) = plt.subplots(nrows=1, ncols=3, figsize=(24,8))

kwargs = {
    'cbar': False,
    'linewidths': 0.2,
    'linecolor': 'white',
    'annot': True, 
}

xlabels=['a','b','c','d','e','f','g','h']
ylabels=['AA','BB','CC','DD','EE','FF','GG','HH']

sns.heatmap(glue, cmap='Reds', xticklabels=xlabels, 
            yticklabels=ylabels, ax=ax1, **kwargs)

xlabels=['p','q','r','s','t','u','v','z']
ylabels=['PP','QQ','RR','SS','TT','UU','VV','ZZ']

sns.heatmap(glue, cmap='Blues', xticklabels=xlabels, 
            yticklabels=ylabels, ax=ax2, **kwargs)

xlabels=['10','20','30','40','50','60','70','80']
ylabels=['11','21','31','41','51','61','71','81']

sns.heatmap(glue, cmap='Greens', xticklabels=xlabels, 
            yticklabels=ylabels, ax=ax3, **kwargs)

Output:

enter image description here

  • Related