我有每个学生的数据,例如
Student Name score Jack 89 Jill 70 Sandy 40
现在我试图使用GD :: Graph :: Bar在条形图中绘制这些图,但由于我对perl和模块很新,我看到我可以手动声明图表中的所有X和Y值被绘制.
但是因为我不知道每个学生的名字和分数(从文本文件中提取)
我希望能够自动执行这些值,
我在想哈希键和值是一个很好的方法.所以我把所有东西都放在哈希表中,%hash(学生名)=(得分)
任何人都可以帮助我将其绘制成条形图或指导我吗?或者你会推荐一种不同的方法吗?
谢谢
“更新
这是我可以通过输入学生姓名手动绘制图表的部分.
my $graph = GD::Graph::bars->new(800,800); @data = ( ["Jack","Jill"],['30','50'],); $graph->set( x_label => 'Students',y_label => 'scores',title => 'Student Vs. scores',y_max_value => 60,y_tick_number => 8,y_label_skip => 2 ) or die $graph->error; my $gd = $graph->plot(\@data) or die $graph->error; open(IMG,'>file.png') or die $!; binmode IMG; print IMG $gd->png;
解决方法
假设您的数据文件如下,使用制表符分隔符.
Student Name score Jack 89 Jill 70 Sandy 40
您可以执行类似的操作,将x轴和y轴值从数据文件推送到数组.
use strict; use warnings; use CGI qw( :standard ); use GD::Graph::bars; open my $fh,'<','data.txt' or die $!; my (@x,@y); while (<$fh>) { next if $. == 1; # skip header line push @x,(split /\t/)[0]; # push 'Student Names' into @x array push @y,(split /\t/)[1]; # push 'score' into @y array } close $fh; my $graph = GD::Graph::bars->new(800,800); $graph->set( x_label => 'Students',y_label => 'scores',title => 'Student Vs. scores',) or warn $graph->error; my @data = (\@x,\@y); $graph->plot(\@data) or die $graph->error(); print header(-type=>'image/jpeg'),$graph->gd->jpeg;
给你举个例子:
如果您想要使用多个y轴值,假设您有另一个选项卡分隔符列,例如score2,您可以轻松地执行类似这样的操作.
my (@x,@y,@y2); while (<$fh>) { next if $. == 1; push @x,(split /\t/)[0]; push @y,(split /\t/)[1]; push @y2,(split /\t/)[2]; }
并将您的@data数组更改为:
my @data = (\@x,\@y,\@y2);
你的结果将是: