gnuplot 能够按照指定的数据生成二维图或三维图,提供丰富的可选图表样式。当然对复杂的三维图,建议使用专业 3D 绘图软件。这是一款非一般意义上的开源的”公开源代码”的免费软件—copyright reserved。有 windows 版,官方网站 http://www.gnuplot.info 。生成的图片参见上文 利用 vmstat+gnuplot+python脚本生成CPU和内存使用率图表
安装好以后运行 gnuplot 即可进入交互模式。然后用下面的简单命令可以在当前目录创建一个 sin(x) 的图表文件 sin.gif(注意:下面的输出代码中的某些英文引号可能被替换成了中文引号):
set terminal gif
set output 'sin.gif'
plot sin(x)
再次换一张图片需要先 reset ,下面从 tsv 文件中获取信息生成图表:
reset
set terminal gif
set output 'hick.gif’
set xdata time # The x axis data is time
set timefmt “%d-%b-%y” # The dates in the file look like 10-Jun-04
set format x “%b %d” # On the x-axis, we want tics like Jun 10
plot [”31-May-04″:”11-Jun-04″] ‘hick.dat’ using 1:2 with linespoints
hick.dat 文件如下:
#Date Open High Low Close
1-Jun-04 88.00 88.48 87.30 88.12
2-Jun-04 88.64 88.64 87.89 87.98
3-Jun-04 87.85 88.10 87.35 87.35
4-Jun-04 87.95 88.49 87.50 87.56
7-Jun-04 88.75 88.99 88.01 88.64
8-Jun-04 88.64 90.50 88.40 90.04
9-Jun-04 89.90 90.55 89.81 90.09
10-Jun-04 90.23 90.75 89.89 90.46
plot 可以通过逗号分割的定义,生成对比曲线:
reset
set terminal gif
set output 'hick.gif'
plot "hick.dat" using 1:2 with lines title "open", \
"hick.dat" using 1:3 with lines title "high", \
"hick.dat" using 1:4 with lines title "low", \
"hick.dat" using 1:5 with lines title "close"
每次在交互模式下输入这么多命令比较麻烦,可以把上述”脚本”保存到 hick.p 文件,下次需要使用的时候,进入 gnuplot 以后,再 load “hick.p” 即可生成图表图片了。下面的例子增加了若干可选参数的设置:
# xy 轴的说明
set xlabel "Date"
set ylabel "Stock Value"
# 输出图片类型: png/gif/jpeg 等
set terminal png
# 输出图片名
set output 'hick.png'
# 输出图片大小为默认值的:宽 * 1.2, 高 * 0.5
set size 1.2, 0.5
# 设置网格
set grid
# 图例说明的位置: top/bottom left/right outside
set key top left
# 设置 x 轴为时间格式
set xdata time
# 输入的时间格式(%d-%d-%y 表示输入时间类似 1-Jun-04 这样的)
set timefmt "%d-%b-%y"
# 输出的时间格式(%m 为月份的数字表示)
set format x "%m/%d"
# 渲染图片
plot "hick.dat" using 1:2 with linespoints title "open", \
"hick.dat" using 1:3 with linespoints title "high", \
"hick.dat" using 1:4 with linespoints title "low", \
"hick.dat" using 1:5 with linespoints title "close"
而更简单的一种方式,为上面的”脚本”指定解释器路径,即可作为一般的 shell 脚本来运行。
gnuplot 允许数据文件是 tab 和空格分割的文本数据,以 # 号开头的行将会被忽略。
下面是 gnuplot 的几个功能说明,更多具体的信息参考官方文档 http://www.gnuplot.info/documentation.html :
. 4.0 版支持数据文件和脚本文件合在一起写
. 4.3 版才支持 utf8 编码
. set datafile 可以设置数据文件的格式,比如指定分割符、注释
. 支持对数据进行函数运算,除了常用的数学函数,还可以自己定义函数
. gnuplot 有 windows 版,不通过 cygwin 也可以在 windows 下运行