在Python中使用Gnuplot

Gnuplot是一个开源的命令行驱动的交互式数据绘图软件。如果你是Gnuplot的用户,并且想在Python中使用它,那么在Gnuplot和PyGnuplot 这两个软件包的帮助下,你可以很容易地做到这一点。

我们也可以使用Matplotlib在Python中绘图,但它没有Gnuplot那么高效。另一方面,Gnuplot是一个二维和三维绘图工具,性能良好,比Matplotlib快得多。

使用Gnuplot的方法Gnuplot.py

Michael Haggerty开发了Gnuplot.py 包。这个包的前提条件如下。

  1. 安装Gnuplot软件。
  2. 安装Python(从2.2到3的任何版本)。
  3. pip 的帮助下,在Python中安装NumPy软件包。

要在Python中安装Gnuplot软件包,我们必须在Windows中遵循这些步骤:

  • 从Gnuplot.py下载Gnuplot.py 包。
  • 打开命令提示符。
  • 移动到命令提示符中的Gnuplot.py 位置。
  • 输入这个命令:
    python setup.py install
    

由于你安装了Gnuplot.py 包,numpy ,你可以使用这个代码来访问Gnuplot软件。

# import libraries
import numpy as np
import Gnuplot
# assign x range 0 to 100
x = np.arange(100)
# assign y range of x square
y = x**2
#load Gnuplot software
g = Gnuplot.Gnuplot()
d = Gnuplot.Data(x,y,with_='lp')
#plot line point on the base of x and y
g.plot(d)

输出:

在Python中使用Gnuplot

使用Gnuplot与pyGnuplot

Gnuplot现在已经不支持了,所以我们可以通过导入pyGnuplot 包在Python中使用Gnuplot,这是Python最新版本的一个内置包。它是Gnuplot软件的一个封装器。

我们必须在 Windows 中按照以下步骤在 Python 中安装pyGnuplot 包。

  • 移动到python.exe 的位置。
  • shift键,在指定的位置上点击右键。
  • 从弹出的菜单中选择open powershell window
  • 使用pip 安装PyGnuplot 。输入这个命令:
    pip install PyGnuplot
    

一旦它被成功安装,我们就可以使用它了。

现在,让我们看看PyGnuplot 包的几个例子。

sin(x) 的代码示例:

from PyGnuplot import gp
# Write path of your gnuplot.exe
fig1 = gp(r'C:Program Filesgnuplotbingnuplot.exe')
#a stand for ask gnuplot; it send command to gnuplot
fig1.a("plot sin(x)")

输出:

在Python中使用Gnuplot

使用Gnuplot的默认数据文件:

#same example Written for Gnuplot.py
#import libraries
from PyGnuplot import gp
import numpy as np
# x range till 100
x = np.arange(100)
#y is equal to the square of x
y = x**2
# Write the path of your gnuplot.exe
fig1 = gp(r'C:Program Filesgnuplotbingnuplot.exe')
#by default, save tmp.dat data file
fig1.save([x,y])
#give the command to gnuplot to plot the data file using columns 1 and 2 to draw line points
fig1.c('plot "tmp.dat" u 1:2 w lp')

输出:

在Python中使用Gnuplot

我们可以使用pdf() 方法,将图形保存为PDF格式。

fig1.pdf('figure.pdf')   # outputs pdf file

我们可以使用fitfit2d 函数来与Gnuplot快速配合。我们可以使用ps 函数使Gnuplot打印成一个postscript。

我们可以在PyGnuplot的文档中看到许多其他方法。

总结

Gnuplot在性能上比Matplotlib好得多,作为Gnuplot的用户,你不需要在Matplotlib上转变。当你是Gnuplot软件的专家时,你不需要学习新的术语,所以我们可以很容易地将Python中的Gnuplot.pyPyGnuplot 包用于Gnuplot软件。