Friday, 17 December 2021

Right and left justified text in a saved `matplotlib`/`seaborn` figure

I have made a heatmap in seaborn, and I need to have text in the corners.

Have:

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

np.random.seed(2021)
data = pd.DataFrame(np.random.randint(0, 5, (3, 5)))\
.rename({0: "Supercalifragilisticexpialidocious",
         1: "Humuhumunukunukuapua'a",
         2: "Hippopotomonstrosesquipedaliophobia"
        })
sns.heatmap(data)
plt.savefig("dave.png")

enter image description here

Want:

enter image description here

The plt.figtext command has worked for this in the past, but I am frustrated in formatting the right and left justification (and distance from the top and bottom), so I just want to have a standard distance from the edges, which sounds like justification. It sounds like that is a matter of changing the coordinates in figtext, which I have not figured out how to do, but I think that is not quite enough. Since the plot can extend very far to the left, I need the GHI and JKL to be to the left of the saved image, not just of the plotting area. The lengths of those words on the left can vary from plot to plot, and I want GHI and JKL left-justified no matter what, whether the long word is "Hippopotomonstrosesquipedaliophobia" or "Dave" (but it shouldn't be way to the left, beyond the left edge of the words, when those words are short).

What would be the way to execute this?

I suppose it would be nice to know how to have such an image appear in a Jupyter Notebook or pop up when I run my script from the command line, but I mostly care about saving the images with those ABC, DEF, GHI, and JKL comments.



from Right and left justified text in a saved `matplotlib`/`seaborn` figure

No comments:

Post a Comment