0

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='-')

warped
  • 8,947
  • 3
  • 22
  • 49
roudan
  • 3,082
  • 5
  • 31
  • 72
  • 1
    This link may help: https://stackoverflow.com/questions/52334938/seaborn-how-to-add-vertical-lines-to-a-distribution-plot-sns-distplot – tcglezen Mar 22 '21 at 21:17
  • Thanks tcglezen. it didn't work. The x axis is date, I am wondering if it is because the date in axvline is not included in dataframe date column? Thanks – roudan Mar 22 '21 at 22:16
  • 1
    You could try `ax.axvline(..., zorder=3)` to make sure they are on top. – JohanC Mar 22 '21 at 23:44
  • Thanks Johan, it didn't worm either. – roudan Mar 23 '21 at 00:01

1 Answers1

1

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

Loïc
  • 146
  • 1
  • 4