【问题标题】:Matplotlib add signature bar at the bottom of figureMatplotlib 在图的底部添加签名栏
【发布时间】:2017-11-26 22:32:33
【问题描述】:

我正在尝试在图形底部添加签名栏。我希望能够做到这一点,而无需使用文本 x 和 y 值以及添加空字符串的所有体力劳动。我正在考虑使用注释,但我遇到了几个问题:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

ax = fig.add_subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)

ax.set_ylim(-2,2)
ax.set_xlabel('Angle')

ax.annotate('What what?', xy=(0, 0), xycoords='figure fraction',backgroundcolor = 'blue')

我的主要问题: 1.我希望条形图穿过图形的整个宽度。我可以添加空白文本来扩展栏,但我希望自动化的东西,所以我不必为不同的场景手动做。 2. 我想将栏移低一点,而不让栏消失或裁剪。

任何建议都会很棒!

【问题讨论】:

  • 究竟什么是“签名栏”?可以更精确地确定所需的输出是什么?
  • 签名栏是指一些在底部或顶部延伸整个图形宽度的框,我可以在其中写下我的姓名和数据源。 Fivethiryeight 数字是此类“签名条”的一个示例。例如:google.com/…:

标签: python matplotlib


【解决方案1】:

调整文本的边界框有点棘手。这个问题显示了一个选项:How do I make the width of the title box span the entire plot?

为了避免这种情况,一个更简单但自动化程度较低的解决方案是在图的下部创建一个矩形并添加一些文本,这样看起来文本就在矩形中。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

ax = fig.add_subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)

ax.set_ylim(-2,2)
ax.set_xlabel('Angle')


def signaturebar(fig,text,fontsize=10,pad=5,xpos=20,ypos=7.5,
                 rect_kw = {"facecolor":"grey", "edgecolor":None},
                 text_kw = {"color":"w"}):
    w,h = fig.get_size_inches()
    height = ((fontsize+2*pad)/72.)/h
    rect = plt.Rectangle((0,0),1,height, transform=fig.transFigure, clip_on=False,**rect_kw)
    fig.axes[0].add_patch(rect)
    fig.text(xpos/72./h, ypos/72./h, text,fontsize=fontsize,**text_kw)
    fig.subplots_adjust(bottom=fig.subplotpars.bottom+height)

signaturebar(fig,"This is my signature text")

plt.show()

【讨论】:

  • 很好的答案。你能解释一下 72. fontsize 的单位是什么?谢谢!
  • 单位是点。 Matplotlib 使用每英寸 72 点 (ppi)。例如。要从点计算像素,您需要图形 dpi pixels = fig.dpi/72. 因为答案使用点作为图形坐标中的单位和位置,所以它与图形 dpi 无关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
相关资源
最近更新 更多