Сейчас, чтобы удовлетворить нужды прихотливых пользователей, практически каждый Интернет-ресурс строится на динамическом отображении представленной информации. Сегодня мы рассмотрим лишь одну из таких возможностей, а именно – реализацию динамических круговых диаграмм.
Язык программирования Perl предлагает разработчикам обширный инструментарий для создания, обработки, изменения и управления содержимым веб-сайтов. С помощью Perl-модуля GD::Graph создание круговой диаграммы становится делом простым и доступным практически каждому.
К примеру, ваш начальник хочет получить сравнительный график, отображающий динамику продаж в онлайне, в обычных магазинах и посредством дистрибьюторов. Сам график должен строиться на основе CSV-файла (Comma Separated Values), который еженедельно экспортируется из Microsoft Excel и размещается в отдельной директории в локальной сети. Нам необходимо написать скрипт, автоматически генерирующий круговую диаграмму на основе имеющихся CSV-данных.
Листинг 1
1 use strict;
2 use GD::Graph::pie;
3 use Text::CSV_XS;
4
5 my @data;
6
7 my $csv = new Text::CSV_XS;
8 open(FILE,"excel.csv") || die "Cannot open excel.csv: $!n";
9 while (my $line = ) {
10 $csv->parse($line);
11 my @col = $csv->fields;
12 push(@data,@col);
13 }
14
15 my $graph = new GD::Graph::pie(300, 300);
16
17 $graph->set(
18 title => 'Заголовок круговой диаграммы',
19 label => 'Пояснительная подпись',
20 axislabelclr => 'black',
21 '3d' => 1,
22 start_angle => 90,
23 suppress_angle => 5,
24 )
25 or warn $graph->error;
26
27 $graph->set_title_font("/usr/share/fonts/ttf/windows/times.ttf",18);
28 $graph->set_value_font("/usr/share/fonts/ttf/windows/times.ttf",12);
29 $graph->set_label_font("/usr/share/fonts/ttf/windows/times.ttf",14);
30
31 $graph->plot(@data) or die $graph->error;
32
33 open(GRAPH,">graph.jpg") || die "Cannot open graph.jpg: $!n";
34 print GRAPH $graph->gd->jpeg(100);
В строке 3 приведенного листинга мы загружаем модуль Text::CSV_XS, скачать бесплатную версию которого можно на CPAN (Comprehensive Perl Archive Network). В строке 7 создаем новый объект класса Text::CSV_XS, открываем CSV-файл в строке 8 и считываем данные из файла в массив @data (строки 9-13). Строка 10 вызывает метод parse(), который разбивает строки файла по колонкам. Сформированные колонки возвращаются с помощью метода fields() в строке 11 и добавляются в виде ряда в массив @data (строка 12). Другими словами, вместо формирования массива @data вручную, мы можем создать его из внешнего файла (в данном случае - CSV).
Далее (в строке 15) создаем объект диаграммы нужной разновидности (в данном случае - pie) с заданным размером изображения.
Третий параметр в строке 21 равен 1, что подразумевает создание трехмерной круговой диаграммы (значение "0" выводит двумерный график и используется по умолчанию). Далее необходимо определить начальную точку построения диаграммы, с которой скрипт будет начинать отсчет секторов графика. Значение задается в градусах и по умолчанию равно "0" (мы установили значение "90", строка 22). Также мы можем установить нужное значение параметра suppress_angle, который определяет минимальный размер сектора круговой диаграммы в градусах.
При желании можно использовать шрифты TrueType вместо встроенных. В строках 27-29 указываются названия гарнитур, использующихся, соответственно, для заголовка диаграммы, наименования секторов и пояснительных подписей к графику. Цифры, идущие после указания гарнитур, означают установленный размер шрифта.
В строке 33 выводится изображение круговой диаграммы в файл в формате JPEG (или PNG). В следующей строке параметром метода jpeg() можно задать степень оптимизации (качества) изображения (в процентах).
В данном случае изображение диаграммы выводится в файл в графическом формате, однако можно его вывести в стандартный поток вывода STDOUT. Это может потребоваться для создания "налету" диаграмм отображения динамически изменяющихся данных на веб-странице. Для этого придется несколько видоизменить вышеприведенный код программы.
Листинг 1
32 print "Content-type: image/jpegnn";
33 binmode(STDOUT);
34 print $graph->gd->jpeg(100);
Чтобы вывести круговую диаграмму на веб-странице, в нужном месте документа следует вставить следующую HTML-конструкцию:
<img src='/cgi-bin/graph.cgi' width=300 height=300 border=0 alt=Диаграмма>
Другие работы по теме:
Задача по теории упругости
Задача №1 Использование плоского напряженного состояния балки-стенки с использованием степенных полиномов Рисунок 1. Решение: Выделим из пластины бесконечно малый элемент aob и рассмотрим его равновесие:
Харари, Фрэнк
Введение 1 Биография 2 Математика 3 Библиография Список литературы Введение Фрэнк Харари (англ. Frank Harary) (11 марта 1921 — 4 января 2005) — американский математик, специализировавшийся на теории графов. Является признанным отцом современной теории графов.[1]
Построение диаграмм
Пусть имеется последовательность положительных действительных чисел a1, a2, ..., an, обозначающая результаты каких-либо измерений (например, высоты вершин гор над уровнем моря, площади государств, средние оценки учеников класса и т.д.). Требуется построить визуализированное представление этой последовательности с целью сравнения полученных результатов.
Визуальное программирование в Delphi
Изучение методов визуального программирования в Delphi. Задание: Построить графики функций ; ; Текст программы: unit Graph; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Demand Curve Essay Research Paper Demand is
Demand Curve Essay, Research Paper Demand is “the quantity of a commodity that will be required at any given price over some given period of time”. “For the majority of the goods and services, experience shows that the quantity demanded will increase as the price falls.” (Stanlake 155) This characteristic can be shown by a demand curve.
Breakeven Point Essay Research Paper Breakeven is
Breakeven Point Essay, Research Paper Breakeven is the point at which a business is neither making money nor losing money, and managing to cover their costs exactly. This is a businesses main objective from
Ammonia Excrfetion As A Function Of Body
Size In Cray Fish Essay, Research Paper Ammonia Excretion As A Function Of Body Size In Crayfish INTRODUCTION The breakdown of proteins and nucleic acids during metabolismgives rise to excess nitrogen which must be rid of by living organisms. Aquatic animals, such as the crayfish we studied in lab, the excess nitrogen is excreted in the form of ammonia (NH3) Because ammonia is highly soluble in water, the ammonia is able to be excreted across the gills into the water.
HertzsprungRussell Diagram Essay Research Paper The HertzsprungRussell
Hertzsprung-Russell Diagram Essay, Research Paper The Hertzsprung-Russell Diagram or, the H-R Diagram for short, is a graph which plots stars according to their temperature and absolute magnitude. This graph reveals a pattern, which in fact is quite interesting. The H-R Diagram is named for the two astronomers, Ejnar Hertzsprung and Henry Russell, who discovered this pattern of stars.
Productivity Growth Hypthesis Essay Research Paper Business
Productivity Growth Hypthesis Essay, Research Paper Business PRODUCTIVITY GROWTH HYPTHESIS In this assignment, we will attempt to study the effects that differencein Income Ratio (henceforth known as I.R.) between the years 1980 and 1990have on the Productivity Growth (P.G.) during the same period of time.
Physics Project Plan Essay Research Paper Physics
Physics Project Plan Essay, Research Paper Physics Project The Planning Key V A ????? Variable resistor ??????? Ammeter???????? Light bulb??????? Voltmeter ???????? I am carrying out an experiment to
Gods Gift To Calculators The Taylor Series
Essay, Research Paper Gods Gift to Calculators: The Taylor Series It is incredible how far calculators have come since my parents were in college, which was when the square root key came out. Calculators since then
Tobaco Indusrty Influence Essay Research Paper Over
Tobaco Indusrty Influence Essay, Research Paper Over the last five years, researchers have calculated that the teenage smoking rates have climbed tremendously. Graph number one shows a steady increase in the number of teenagers who smoke heavily. Graph number two shows how teenage smoking has made a comeback, and how the number of teen-agers smoke occasionally and who develop heavier habits has increased sharply in recent years.
Osmosis In Tomatos Essay Research Paper This
Osmosis In Tomatos Essay, Research Paper This graph shown above gives the line of best fit for the percentage change in mass of the potato chips over the course of the thirty minute experiment. The graph is a curve that slopes downwards and does not go through the origin. Because the line is not straight and does not pass through the origin, it means that the percentage gain and loss in mass and concentration are not directly proportional.
Velocity Essay Research Paper Instantaneous Versus Average
Velocity Essay, Research Paper Instantaneous Versus Average Velocity A position versus time graph or a displacement versus time graph can be used to analyze the motion of an object in one dimension. The slope gives the object’s velocity. The slope of a line segment joining two points on the graph gives the average velociy during that interval.
Momentum Essay Research Paper AbstractMeasurements of velocity
Momentum Essay, Research Paper Abstract Measurements of velocity and mass of two objects colliding, support the conservation of linear momentum. The dynamics of different masses distinguish velocity values experimentally. Video recordings of two colliding masses can be manipulated to extract frames displaying distance verses time.
Investigating The Effect Of Resistance On Wires
Essay, Research Paper I am going to be studying the resistance of wire. The purpose of this investigation is to see how length and thickness of wire affect the dependent variable, resistance. Prediction
Heat Loss In Coffee Essay Research Paper
Prediction I predict that the best way to keep coffee warm is to have a silver insulator because of what we know on radiation and silver being a poor emitter compared to a plain beaker or a black one. I predicted this because
Physics Time Period Of A Pendulum Essay
, Research Paper PLAN: String Ruler BA Weight Stand Desk Timer The time period for a pendulum is the time taken for the pendulum to swing from one point to another (i.e. from A to B and back again)
Osmosis Essay Research Paper Title
Osmosis Essay, Research Paper Title: Osmosis in Potato Cells I am going to investigate: the diffusion of water by osmosis in plant cells, when changing the concentrations of sucrose in water, and measuring the change of mass of pieces of potato left in the solution for twelve hours.
Pressure Essay Research Paper Aim To find
Pressure Essay, Research Paper Aim: To find out the effect of temperature on the pressure of air. Apparatus: ? 400ml beaker ? Bunsen burner ? Data Logger ? Pressure sensor
How Are Automatic Stabilizers Used To Combat
Inflation Essay, Research Paper How are Automatic Stabilizers Used to Combat Inflation? In today?s economy, there are devices present called automatic stabilizers. Automatic stabilizers, are mechanisms which aid in the correction of an economic problem without the interference of anyone or anything.
Spanning Tree Essay Research Paper A spanning
Spanning Tree Essay, Research Paper A spanning tree is an application of a network. There is another type of spanning tree called the minimum spanning tree. This data structure is used in many business applications. I will be discussing what a spanning tree is and what a minimum spanning tree is, and how they work.
Differentiation By First Principles Essay Research Paper
The question says you should differentiate y = x2 by first principles. This means you are not allowed just to write down the answer using any ’short-cut’ rules, but must use the ‘official’ method as follows: First, consider a sketch of the graph of y = xІ (right). You have to find an expression for , which represents
Деревья /english/
Представление информационных конструкций в виде дерева, что такое "дерево", примеры построения и определения "дерева".