python 绘制带有自定义文本的图形

python draw a graph with custom text

我正在寻找可以帮助绘制自定义信息(如图形)以及自定义文本(如下图所示)的东西。

所有流行的图形绘制工具都只是图形绘制工具,但我需要的是可以在某个位置绘制文本的东西,在某个位置绘制图形的东西,我不需要花哨的图形,只要像图片上那样简单即可。

javascript 中的 D3 实际上也在做类似的事情,但我不确定这是 Python 的最佳解决方案。然后我需要把它导出到png文件。

如有任何帮助,我将不胜感激

您可以使用 matplotlib 来执行此操作 - 它将允许非常灵活地控制文本。

作为您要求的示例,试试这个脚本 (based on this gallery example):

import numpy as np
import matplotlib.pyplot as plt

t1 = np.arange(0.0, 5.0, 0.1)

plt.figure(1)
sub = plt.subplot(121)

# Add 'Text' entries
sub.text(x=0.1, y=1, s="Text 1")
sub.text(x=0, y=.5, s="Text 2")
sub.text(x=0.2, y=.25, s="Text 3")
sub.text(x=0.15, y=0, s="Text 4")
sub.axis('off')

plt.subplot(122)
plt.plot(t1, np.cos(2*np.pi*t1), 'r--')
plt.show()

注意:我根本没有编辑字体或大小。有关文本控制的详细信息,请参阅 this documentation page

或者,您可以在图表轴外添加 (x, y) 坐标的文本,并跳过添加子图。像这样: 将 numpy 导入为 np 将 matplotlib.pyplot 导入为 plt

t1 = np.arange(0.0, 5.0, 0.1)

plt.figure(1)

plt.plot(t1, np.cos(2*np.pi*t1), 'r--')
plt.text(x=-5, y=.5, s="Way over here")
plt.show()

Matplotlib is great for all that. Not clear what you mean by fancy. If you're dealing with dates on the x-axis, you could use datetime 个对象。

import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(10,10))
plt.plot(np.random.random(100))
plt.text(120,0.5,'Text1')
plt.text(120,0.3,'Text2',fontdict={'size':15})
plt.savefig('plot.png')
plt.show()