Search code examples
pythonseaborn

How to add Vertical Line into Seaborn Heatmap


How to add vertical lines into searborn heatmap. I did the following way and no lines showed up. No error though. I am wondering if the lines are covered by heatmap color? any suggestions? Thanks

fig,ax=plt.subplots(1,1,figsize=(30,15))
g=sns.heatmap(df,cmap='coolwarm', robust=robust_colorbarrange,yticklabels=yticklabels,xticklabels=xticklabels,annot=False,   \
                      cbar_kws={'fraction':0.02, "shrink": 1.0,'pad':0.01},vmin=colorbar_min, vmax=colorbar_max, ax=ax) 


for datestr in CycleDates:
    date=datetime.strptime(datestr,'%Y-%m-%d %H:%M')
    ax.axvline(date,color='k',linestyle='-')


Solution

  • I find a solution that consist to overlay an matplotlib.Axe and then, plot lines on it:

    fig, ax = plt.subplots(1, 1, figsize=(30, 15))
    
    ax = sns.heatmap(df, ax=ax, **kwargs)
    
    # create 2nd axis
    ax2 = ax.twinx()
    ax2.set_ylim(df.index.min(), df.index.max()) 
    # and hide it
    ax2.get_yaxis().set_visible(False)
    ax2.grid(False)
    
    # loop to create a line for each date as request by OP
    i = 0
    for datestr in CycleDates, :
        date=datetime.strptime(datestr,'%Y-%m-%d %H:%M')
        ax.axvline(date,color='k',linestyle='-')
        
        ax2.vlines(date, i,i+1, color='k', linestyles='dashed')
    

    I didn't check this answer with the OP code since it wasn't a standalone exemple. However, I apply that solution to one of my problem and it works.

    hlines on heatmpa