matplotlib 有没有办法把数据放在标签前面?

bhmjp9jg  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(162)

Matplotlib中的标签似乎总是显示在最顶部的叠加层上,覆盖了其后面的数据。
示例:

图中有两个红色的文本注解。底部的一个被灰色的“Meteo”文本覆盖。
是否有办法将红色注解移动到灰色文本标签上方?
我在玩zorder,但没有成功。

piok6c0g

piok6c0g1#

这似乎只适用于annotations,而不适用于text
下面是一个示例:

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()
70gysomp

70gysomp2#

它工作正常,但不是以你可能期望的方式。
每个元素都有它的zorder,甚至ax也有默认的zorder=0,这意味着,所有的元素,我们称之为一个,都有最终的zorder=0
但是当绘制axlayer 时,zorder分别应用于每个元素,并且从下到上正确地放置在视图中。
所以现在你有了ax渲染与最终zorder=0
然后你用fig.text添加文本,它将文本添加到图形,所以现在你有两个对象要渲染;axzorder = 0以及textzorder=0。您可以设置文本zorder=-1,它将文本放置在ax之下,但是如果ax有实心背景,它将不可见。请尝试在fig**图层中添加另一个text**具有更高或更低的zorder,并且它将被适当地绘制在另一个text元素之上或之下。

相关问题