|
|
[user]$ vim bars.pl
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
use GD::Graph::bars; # 棒グラフ
# 画像サイズ
use Readonly;
Readonly my $WIDTH => 250;
Readonly my $HEIGHT => 250;
# データ
my @student = qw( 田中 鈴木 山田 佐藤 );
my @japanese = qw( 70 62 55 90 );
my @arithmetic = qw( 75 93 75 80 );
my @english = qw( 80 55 65 85 );
my @data = ( \@student, \@japanese, \@arithmetic, \@english );
# GD::Graph::bars オブジェクト作成
my $graph_obj = GD::Graph::bars->new( $WIDTH, $HEIGHT );
# 凡例
$graph_obj->set_legend( '国語', '数学', '英語' );
# パラメータ設定
my $ymax = 300;
$graph_obj->set(
title => 'テスト結果(積重ねる)', # タイトル
x_label => '生徒', # x 軸のラベル
y_label => '点数', # y 軸のラベル
y_min_value => 0, # y 軸の最小値
y_max_value => $ymax, # y 軸の最大値
y_tick_number => 10, # y 軸に付ける目盛り数
y_label_skip => 2, # 目盛りをスキップ
long_ticks => 1, # メモリを全体に広げる
bar_width => 20, # 棒の幅
bgclr => '#ffffff', # 背景色
dclrs => ['#ff9999', '#99ff99', '#9999ff'], # グラフの色
show_values => 1, # 値を表示
values_format => '%02d', # 値表示用フォーマット
bargroup_spacing => 8, # 項目毎の間隔
cumulate => 1, # 1 : 積重ねる, 0 : 積重ねない
);
# 日本語使用([user]$ locate .ttf で調べる)
Readonly my $TTF => '/usr/share/fonts/vlgothic/VL-Gothic-Regular.ttf';
$graph_obj->set_title_font( $TTF, 8 ); # タイトル
$graph_obj->set_x_axis_font( $TTF, 8 ); # x 軸
$graph_obj->set_x_label_font( $TTF, 8 ); # x 軸のラベル
$graph_obj->set_y_label_font( $TTF, 8 ); # y 軸のラベル
$graph_obj->set_legend_font( $TTF, 8 ); # 凡例
# 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 = 'bar2.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 bars.pl
[user]$ ./bars.pl