Home > Enterprise >  How to plot a line plot over sns.heatmap over the center of tick labels
How to plot a line plot over sns.heatmap over the center of tick labels

Time:09-29

Currently, I am trying to plot the viterbi path over all state probabilities. Basically, it is a line plot over a Seaborn heatmap I am using the following code

fig = plt.figure(figsize=(10, 10))
ax = sns.heatmap(plot.T, cmap="viridis")
ax.set_title("State probabilities")
ax.set_xlabel("Time step")
ax.set_ylabel("Hidden states")
plt.plot(viterbi_path, color='red')
plt.show()

And I am getting something like this: What I have

While the line to start from the center and with no transitions rather on actual values like in this image Image of What I need

How can I achieve this?

Thank you for the help :)

A basic reproducible toy code for experiment

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

uniform_data = np.random.rand(10, 15)
ax = sns.heatmap(uniform_data)
t = np.arange(10)
t = [0, 0, 1, 1, 2, 3, 4,4,4,4,5,6,7,8,9]
plt.plot(t)
plt.show()

Generates this heatmap

CodePudding user response:

Seaborn draws the ticks at the half positions (0.5, 1.5, ...). You can add a half to have the lines at the centers in the y-direction.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

uniform_data = np.random.rand(10, 15)
ax = sns.heatmap(uniform_data)
t = [0, 0, 1, 1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 8, 9]
plt.plot(np.array(t)   0.5, color='lime', lw=3)
plt.show()

sns.heatmap with lines

You can do the same to also center in the x-direction:

plt.plot(np.arange(len(t))   0.5, np.array(t)   0.5, color='lime', lw=3)

sns.heatmap with lines centered in x and y

  • Related