[user]$ vim lines.pl
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
use GD::Graph::lines; # 線グラフ
# 画像サイズ
use Readonly;
Readonly my $WIDTH => 250;
Readonly my $HEIGHT => 250;
# データ
my @x = map { $_ * 0.1 } -50..50; # -5 ~ 5 まで 0.1 刻み
my @y = map { ($_ ** 2) - 3 } @x; # y = x^2 - 3
my @data = ( \@x, \@y );
# GD::Graph::lines オブジェクト作成
my $graph_obj = GD::Graph::lines->new( $WIDTH, $HEIGHT );
# パラメータ設定
$graph_obj->set(
title => 'y = x^2 - 3', # タイトル
x_label => 'x', # x 軸のラベル
y_label => 'y', # y 軸のラベル
long_ticks => 1, # 目盛りを全体に広げる
x_min_value => -5, # x 軸の最小値
x_max_value => 5, # x 軸の最大値
x_tick_number => 10, # x 軸に付ける目盛り数
y_min_value => -5, # y 軸の最小値
y_max_value => 25, # y 軸の最大値
y_tick_number => 10, # y 軸に付ける目盛り数
y_label_skip => 2, # 目盛りをスキップ
zero_axis => 1, # Y 軸の 0 を示す線を常に表示
zero_axis_only => 1, # Y 軸の 0 の線を軸として使用
bgclr => '#ffffff', # 背景色
dclrs => ['#ff0000'], # グラフの色
);
# GD::Image オブジェクト作成
my $img_obj = $graph_obj->plot( \@data ) or croak $graph_obj->error;
# ファイルへ出力
use Carp qw( croak );
use Fcntl;
use IO::Handle;
my $tmpfn = "tmp.$$"; # テンポラリーファイル名
my $imgfn = 'two_dimensions.png'; # 画像ファイル名
sysopen ( my $fh, $tmpfn, O_WRONLY | O_TRUNC | O_CREAT, 0644 ) or croak qq{can't open :$!};
flock $fh, 2;
print {$fh} $img_obj->png() or croak qq{can't write :$!};
# ファイルファンドルへの出力をバッファしない
$fh->flush or croak qq{can't flush :$!};
# メモリ上にあるファイルの内容をストレージデバイス上のものと同期させる
$fh->sync or croak qq{can't fsync :$!};
close $fh or croak qq{can't close :$!};
# ファイル名変更
rename $tmpfn, $imgfn or croak qq{can't rename $tmpfn to $imgfn :$!};
[user]$ chmod 700 lines.pl
[user]$ ./lines.pl