Search code examples
pythonseabornheatmapplotly-python

How do you put the x axis labels on the top of the heatmap created with seaborn?


I have created a heatmap using the seaborn and matplotlib package in python, and while it is perfectly suited for my current needs, I really would prefer to have the labels on the x-axis of the heatmap to be placed at the top of the plot, rather than at the bottom (which seems to be its default).

So an abridged form of my data looks like this:

NP                  NP1       NP2       NP3       NP4       NP5
identifier                                                     
A1BG~P04217   -0.094045  0.012229  0.102279  1.319618  0.002383
A2M~P01023    -0.805089 -0.477339 -0.351341  0.089735 -0.473815
AARS1~P49588   0.081827 -0.099849 -0.287426  0.101588  0.136366
ABCB6~Q9NP58   0.109911  0.458039 -0.039325 -0.484872  1.905586
ABCC1~I3L4X2  -0.560155  0.580285  0.012868  0.291303 -0.407900
ABCC4~O15439   0.055264  0.138630 -0.204665  0.191241  0.304999
ABCE1~P61221  -0.510108 -0.059724 -0.233365  0.078956 -0.651327
ABCF1~Q8NE71  -0.348526 -0.135414 -0.390021 -0.190644 -0.276303
ABHD10~Q9NUJ1  0.237959 -2.060834  0.325901 -0.778036 -4.046345
ABHD11~Q8NFV4  0.294587  1.193258 -0.797294 -0.148064 -1.153391

And when I use the following code:

import seaborn as sns
import matplotlib as plt

fig, ax = plt.subplots(figsize=(10,30))
ax = sns.heatmap(df_example, annot=True, xticklabels=True)

I get this kind of plot: https://imgpile.com/i/T3zPH1

I should note that the this plot was made from the abridged dataframe above, the actual dataframe has thousands of identifiers, making it very long.

But as you can see, the labels on the x axis only appear at the bottom. I have been trying to get them to appear on the top, but seaborn doesn't seem to allow this kind of formatting.

So I have also tried using plotly express, but while I solve the issue of placing my x-axis labels on top, I have been completely unable to format the heat map as I had before using seaborn. The following code:

import plotly.express as px

fig = px.imshow(df_example, width= 500, height=6000)
fig.update_xaxes(side="top")
fig.show()

yields this kind of plot: https://imgpile.com/i/T3zF42.

I have tried many times to reformat it using the documentation from plotly (https://plotly.com/python/heatmaps/), but I can't seem to get it to work. When one thing is fixed, another problem arises. I really just want to keep using the seaborn based code as above, and just fix the x-axis labels. I'm also happy to have the x-axis label at both the top and bottom of the plot, but I can't get that work presently. Can someone advise me on what to do here?


Solution

  • Ok, so I did a bit more research, and it turns out you can add the follow code with the seaborn approach:

    plt.tick_params(axis='both', which='major', labelsize=10, labelbottom = False, bottom=False, top = False, labeltop=True)