python - 如何将 pylab.plot 线放在 pylab.figtext 上?

标签 python matplotlib plot

我希望情节线覆盖文本。这是当前代码:

pylab.plot( data[:,0], data[:,1], color='red', lw=3, label='Temp' )
pylab.figtext(0.7, 0.5, round(temp1,2), color='white', fontsize=450,
    bbox={'facecolor':'black', 'alpha':0.8, 'pad':12})

我使用了非常大的白色数字,红色绘图线被这些数字隐藏了。我只是希望情节线位于数字之上。我尝试将 alpha=0.2 添加到Figtext 行,然后我可以看到绘图线,但白色数字和绘图线看起来都很暗。

最佳答案

使用 zorder kwarg 来控制什么与什么交叉。

默认情况下,文本的 zorder 高于线条、图像和其他绘图功能(其想法是文本通常是应该位于顶部的标签)。

但是,还有一个额外的问题。您当前正在使用 figtext。这会将文本放置在图形级别而不是轴级别。您需要使用 plt.text/ax.text 代替。如果您想指定当前的图形坐标位置,可以传入 transform=fig.transFigure

以下是默认情况下的外观示例:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(range(10), color='red', lw=3)
# Placing the text in data coordinates...
ax.text(5, 5, 'Test', color='white', fontsize=45,
        bbox={'facecolor':'black', 'pad':12})

plt.show()

enter image description here

下面是当我们更改 zorder 时会发生的情况(如果我没记错的话,文本的默认值是 3。任何大于或等于 4 的 zorder 都会覆盖任何文本图中的对象。)

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(range(10), color='red', lw=3, zorder=4)
# Placing the text in data coordinates...
ax.text(5, 5, 'Test', color='white', fontsize=45,
        bbox={'facecolor':'black', 'pad':12})

plt.show()

enter image description here

但是,如果我们使用 plt.figtextfig.text (它们是相同的),文本将放置在图形级别而不是轴上等级。因此,无论该行的 zorder 是什么,文本仍将位于轴中任何内容的前面。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(range(10), color='red', lw=3, zorder=5000)
# Placing the text in figure coordinates
fig.text(0.5, 0.5, 'Test', color='white', fontsize=45,
        bbox={'facecolor':'black', 'pad':12})

plt.show()

enter image description here

因此,如果您想使用图形坐标并且仍然让线条位于顶部,则应该使用 ax.textax.annotate 并指定 transform=fig.transFigure 以便您使用的坐标被解释为数字分数:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(range(10), color='red', lw=3, zorder=4)
# Placing the text in figure coordinates
ax.text(0.5, 0.5, 'Test', color='white', fontsize=45, transform=fig.transFigure,
        bbox={'facecolor':'black', 'pad':12})

plt.show()

enter image description here

关于python - 如何将 pylab.plot 线放在 pylab.figtext 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27756620/

相关文章:

python - SWIG 和 Mingw-64 与 Python 一起使用……不是有效的 Win32 应用程序

python - 在 Altair LayerChart 中指定绘图标题和构面标题

python - 文本框不随包含框架扩展 - TKinter

python - 使用 pyinstaller 为 Solaris 操作系统分发 python 应用程序会出现 subprocess.py 错误

python - matplotlib 中的层次结构

python - Matplotlib 条形图去除内部线条

python - 在 plt.contourf 中使用非线性级别时保持颜色图的线性颜色

python - 使用 numpy 和 matplotlib 的总和直方图而不是计数

Matplotlib:在图表上的每个点旁边显示值

r - ggplot2 & facet_wrap - 消除小平面之间的垂直距离