gpt4 book ai didi

perl - 使用 GD::Graph 绘制条形图

转载 作者:行者123 更新时间:2023-12-02 03:07:37 28 4
gpt4 key购买 nike

我有每个学生的数据,例如:

    Student Name         Score
Jack 89
Jill 70
Sandy 40

现在我尝试使用 GD::Graph::Bar 将这些绘制在条形图中,但我发现我可以手动将图表中的所有 X 和 Y 值声明为已绘制。

由于我不知道每个学生的姓名和分数(从文本文件中提取),因此我希望能够自动计算这些值,

我认为散列键和值是一个好方法。我将所有内容放入哈希表中:%hash(student name)=(score)

任何人都可以帮我将其绘制为条形图或指导我吗?或者您会推荐一种不同的方法吗?

这是我可以通过输入学生姓名手动绘制图表的部分:

 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;

给你举个例子: enter image description here

如果您想使用多个 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);

你的结果将是:enter image description here

关于perl - 使用 GD::Graph 绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18150841/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com