Home > other >  In matplotlib, is there a way to put the data in front of a label?
In matplotlib, is there a way to put the data in front of a label?

Time:03-14

It seems that the labels in Mathplotlib always are shown on the most top overlay, covering the data behind it.

Example:

enter image description here

The plot has 2 text annotations in red. The bottom one is overlayed by a gray "Meteo" text.

Is there a way to move the red annotation above the gray text label?

I was playing with the enter image description here

import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects

fig, ax = plt.subplots()

# foreground annotation
a1 = ax.annotate("annotation", (0.5, 0.5), fontsize='xx-large', color="red", zorder=9)
a1.set_path_effects([path_effects.Stroke(linewidth=5, foreground='white'), path_effects.Normal()])

# background annotation
a2 = ax.annotate("Another annotation", (0.6, 0.48), fontsize='xx-large', color="blue", zorder=5)
a2.set_path_effects([path_effects.Stroke(linewidth=5, foreground='white'), path_effects.Normal()])

# zorder ignored:
t1 = fig.text(0.56, 0.49, "Background", color='gray', ha='right', zorder=0)
t1.set_path_effects([path_effects.Stroke(linewidth=3, foreground='white'), path_effects.Normal()])

plt.show() 

CodePudding user response:

It works properly, but not in a way You might expect.

Every element has it's zorder. Even ax has default zorder=0. It means, that all elements within that, let's call it a layer, will have final zorder=0.

But when ax layer is drawn, zorder is applied to every element respectively and are placed correctly in the view from bottom to the top.
So now You have ax layer rendered with final zorder=0.

Then You are adding text with fig.text. Which adds text to the figure layer. So now You have two objects to render; ax layer with zorder = 0 and text with zorder=0 as well. You can set text zorder=-1 which will put text below ax layer, but it will be invisible if ax has solid background. Try to add another text in the fig layer with higher or lower zorder and it will be properly drawn on top or below another text element.

  • Related