使用perl画图

本文详细介绍了如何使用Perl语言结合GD::Graph库进行图表绘制,通过实例展示了如何从数据文件中读取信息并生成条形图。文章还提到了如何处理多y轴值的情况,以及在绘图过程中设置轴标签、标题等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

zz :http://stackoverflow.com/questions/18150841/gdgraph-with-perl

GD::Graph with Perl


Assuming your data file is as follows, using tab delimiters.

Student Name         Score
Jack                  89
Jill                  70
Sandy                 40

You could do something like this, pushing your x axis and y axis values from your data file to arrays.

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;

Giving you for example: enter image description here

If you are wanting to use multiple y axis values, assuming you have another tab delimiter column with for example Score2, you could easily do something like this.

my (@x, @y, @y2);
while (<$fh>) {
   next if $. == 1;
   push @x, (split /\t/)[0];
   push @y, (split /\t/)[1];
   push @y2, (split /\t/)[2];
}

And change your @data array to:

my @data = (\@x, \@y, \@y2);

And your result would be: enter image description here


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值