Next: MGL scripts, Up: (dir) [Contents][Index]
Это документация для языка MGL (версии 2.3.5). Пожалуйста сообщайте о любых ошибках в этом руководстве на mathgl.abalakin@gmail.org. Дополнительную информацию о MGL и MathGL можно найти на домашней странице проекта http://mathgl.sourceforge.net/.
Copyright © 2008-2012 Alexey A. Balakin.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License.”
• MGL scripts: | ||
• General concepts: | ||
• MathGL core: | ||
• Data processing: | ||
• Examples: | ||
• Symbols and hot-keys: | ||
• Copying This Manual: | ||
• Index: |
Next: General concepts, Previous: Top, Up: Top [Contents][Index]
MathGL имеет встроенный скриптовый язык MGL для обработки и отображения данных. Скрипты MGL могут быть выполнены независимо (с помощью программ UDAV, mglconv, mglview и др.
• MGL definition: | ||
• Program flow commands: | ||
• LaTeX package: |
Next: Program flow commands, Up: MGL scripts [Contents][Index]
Язык MGL достаточно простой. Каждая строка – отдельная команда. Первое слово – имя команды, а все остальные ее аргументы. Команда может иметь до 1000 аргументов (по крайней мере сейчас). Слова разделяются одно от другого пробелом или символом табуляции. Различий между верхним и нижним индексом нет, т.е. переменные a и A идентичны. Символ ‘#’ начинает комментарий – все символы после него игнорируются до конца строки. Исключением является случай, когда ‘#’ входит в строку. Опции команды указываются после символа ‘;’ (see Command options). Символ ‘:’ начинает новую команду (подобно переводу строки) если он расположен не внутри скобок или строки.
Если строка содержит ссылки на внешние параметры (‘$0’, ‘$1’ ... ‘$9’) или макроопределения (‘$a’, ‘$b’ ... ‘$z’), то текущие значения параметров/макроопределений подставляются в строку вместо ссылки до выполнением команды. Это позволяет использовать один и тот же скрипт при различных входных параметрах командной строки или вводить макроопределения по ходу исполнения команд скрипта.
Аргументы команды могут быть строками, переменными или числами.
new x 100 'x':copy !b !exp(1i*x)
создаст массив действительных чисел x и массив комплексных чисел b, который будет равен exp(I*x), где I^2=-1.
В качестве переменной можно использовать также и временные массивы, включающие в себя:
a(1)
или a(1,:)
или a(1,:,:)
– вторая строка массива a, a(:,2)
или a(:,2,:)
– третий столбец, a(:,:,0)
– первый срез и т.д. Также можно выделить часть массива с m-го по n-ый элемент a(m:n,:,:)
или просто a(m:n)
.
a('n*w^2/exp(t)')
), если столбцы данных были именованы командой idset или в файле данных (в строке начинающейся с ##
).
tmp[i,j] = sqrt(dat[i,5,j]+1)
.
Временные массивы не могут стоять в качестве первого аргумента команд, создающих массивы (например, ‘new’, ‘read’, ‘hist’ и т.д.).
nan=#QNAN, inf=бесконечность, rnd=случайное число, pi=3.1415926..., on=1, off=0, :=-1
, переменные с суффиксами (see Data information), переменные определенные командой define. Также массивы размером 1x1x1 считаются скалярами (например, ‘pi/dat.nx’).
Перед первым использованием все переменные должны быть определены с помощью команд, создающих массивы (new, var, list, copy, read, hist, sum и др., см. Data constructor, Data filling и Make another data).
Команды могут иметь несколько наборов аргументов (например, plot ydat
и plot xdat ydat
). Все аргументы команды для выбранного набора должны быть указаны, однако часть из них могут иметь значения по умолчанию. Такие аргументы в описании команд будут помещены в квадратные скобки [], например plot ydat ['stl'='' zval=nan]
. При этом запись [arg1 arg2 arg3 ...]
подразумевает [arg1 [arg2 [arg3 ...]]]
, т.е. опускать можно только аргументы с конца, если вы согласны с их значениями по умолчанию. Например, plot ydat '' 1
или plot ydat ''
правильно, а plot ydat 1
не правильно (аргумент 'stl'
пропущен).
Можно предоставить несколько вариантов аргументов комманд при использовании символа ‘?’ для их разделения. Конкретный вариант аргумента, используемый при выполнении команды, задается значением команды variant. При этом будет использован последний вариант, если задано слишком большое значение. По умолчанию используется первый вариант (т.е. как при variant 0
). Например в следующем коде будет сначала нарисован график синим цветом (первый аргумент ‘b’), а затем красным пунктиром – после variant 1
будет использован второй аргумент ‘r|’:
fplot 'x' 'b'?'r' variant 1 fplot 'x^3' 'b'?'r|'
Next: LaTeX package, Previous: MGL definition, Up: MGL scripts [Contents][Index]
Ниже собраны команды, управляющие порядком выполнения других команд (условия, циклы, подпрограммы), (пере-)определяют аргументы скрипта и пр. Прочие команды могут быть найдены в главах MathGL core и Data processing. Отмечу, что некоторые из команд (например, define, ask, call, for, func) должны быть расположены на отдельной строке.
Переходит в папку path.
Задает N-ый аргумент скрипта равным ответу пользователя на вопрос question. Обычно команда показывает диалог с вопросом и полем ввода текста ответа. Здесь N это цифра (0...9) или буква (a...z).
Задает N-ый аргумент скрипта равным smth. Отмечу, что smth используется как есть (с символами ‘'’ если присутствуют). Выполняется только подстановка других макроопределений $0...$9, $a...$z. Здесь N это цифра (0...9) или буква (a...z).
Определяет константу (скаляр) с именем name
и числовым значением smth
. Позднее она может быть использована как обычное число.
Задает N-ый аргумент скрипта равным символу с UTF кодом smth. Здесь N это цифра (0...9) или буква (a...z).
Задает N-ый аргумент скрипта равным числовому значению smth. Здесь N это цифра (0...9) или буква (a...z).
Переходит к выполнению (вызывает) подпрограммы fname (или внешнего скрипта, если функция не была найдена). Опциональные аргументы передаются в подпрограмму. См. также func.
Определяет подпрограмму с именем fname и задает число требуемых аргументов. Аргументы будут помещены в параметры скрипта $1, $2, ... $9. Отмечу, что выполнение основной программы будет остановлено при встрече func
– действует аналогично комманде stop. См. также return.
Возвращается из подпрограммы. См. также func.
Загружает дополнительные команды MGL из внешней динамической библиотеки filename. Данная библиотека должна содержать массив с именем mgl_cmd_extra
типа mglCommand
, который содержит описание новых комманд.
Начинает блок команд, выполняемый если каждый элемент dat удовлетворяет условию cond.
val
Начинает блок команд, выполняемый если val
не ноль.
Начинает блок команд, выполняемый если предыдущий if
или elseif
не был выполнен и каждый элемент dat удовлетворяет условию cond.
val
Начинает блок команд, выполняемый если предыдущий if
или elseif
не был выполнен и val
не ноль.
Начинает блок команд, выполняемый если предыдущий if
или elseif
не был выполнен.
Заканчивает определение блока if/elseif/else
.
v1 v2 [dv=1]
Начинает блок команд, выполняемый в цикле с $N-ым аргументом изменяющимся от v1 до v2 с шагом dv. Здесь N это цифра (0...9) или буква (a...z).
Начинает блок команд, выполняемый в цикле с $N-ым аргументом пробегающим значения массива dat. Здесь N это цифра (0...9) или буква (a...z).
Заканчивает блок цикла for
.
val
Определяет код (между once on
и once off
) который будет выполнен только один раз. Полезно для работы с большими данными в программах типа UDAV.
Останавливает выполнение скрипта.
val
Задает вариант аргумента(ов), разделенных символом ‘?’, для всех последующих комманд.
dt=1
]Выполняет один шаг решения системы обыкновенных дифференциальных уравнений {var1’ = eq1, ... } с временным шагом dt. Здесь переменные ‘var1’, ... – переменные, определенные в MGL скрипте ранее. При решении используется метод Рунге-Кутта 4-го порядка.
Previous: Program flow commands, Up: MGL scripts [Contents][Index]
There is LaTeX package mgltex
(was made by Diego Sejas Viscarra) which allow one to make figures directly from MGL script located in LaTeX file.
For using this package you need to specify --shell-escape
option for latex/pdflatex or manually run mglconv tool with produced MGL scripts for generation of images. Don’t forgot to run latex/pdflatex second time to insert generated images into the output document. Also you need to run pdflatex third time to update converted from EPS images if you are using vector EPS output (default).
The package may have following options: draft
, final
— the same as in the graphicx package; on
, off
— to activate/deactivate the creation of scripts and graphics; comments
, nocomments
— to make visible/invisible commentaries contained inside mglcomment
environments; jpg
, jpeg
, png
— to export graphics as JPEG/PNG images; eps
, epsz
— to export to uncompressed/compressed EPS format as primitives; bps
, bpsz
— to export to uncompressed/compressed EPS format as bitmap (doesn’t work with pdflatex); pdf
— to export to 3D PDF; tex
— to export to LaTeX/tikz document.
The package defines the following environments:
It writes its contents to a general script which has the same name as the LaTeX document, but its extension is .mgl. The code in this environment is compiled and the image produced is included. It takes exactly the same optional arguments as the \includegraphics
command, plus an additional argument imgext, which specifies the extension to save the image.
An example of usage of ‘mgl’ environment would be:
\begin{mglfunc}{prepare2d} new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' \end{mglfunc} \begin{figure}[!ht] \centering \begin{mgl}[width=0.85\textwidth,height=7.5cm] fog 0.5 call 'prepare2d' subplot 2 2 0 : title 'Surf plot (default)' : rotate 50 60 : light on : box : surf a subplot 2 2 1 : title '"\#" style; meshnum 10' : rotate 50 60 : box surf a '#'; meshnum 10 subplot 2 2 2 : title 'Mesh plot' : rotate 50 60 : box mesh a new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)' new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)' new z 50 40 '0.8*cos(pi*(y+1)/2)' subplot 2 2 3 : title 'parametric form' : rotate 50 60 : box surf x y z 'BbwrR' \end{mgl} \end{figure}
It adds its contents to the general script, without producing any image.
Is exactly the same as ‘mgl’, but it writes its contents verbatim to its own file, whose name is specified as a mandatory argument.
Is exactly the same as ‘mglcode’, but it doesn’t produce any image, nor accepts optional arguments. It is useful, for example, to create a MGL script, which can later be post processed by another package like "listings".
It writes its contents verbatim to a file, specified as a mandatory argument, and to the LaTeX document, and numerates each line of code.
Exactly the same as ‘mglblock’, but it doesn’t write to a file. This environment doesn’t have arguments.
Is used to define MGL functions. It takes one mandatory argument, which is the name of the function, plus one additional argument, which specifies the number of arguments of the function. The environment needs to contain only the body of the function, since the first and last lines are appended automatically, and the resulting code is written at the end of the general script, after the stop command, which is also written automatically. The warning is produced if 2 or more function with the same name is defined.
Is used to contain multiline commentaries. This commentaries will be visible/invisible in the output document, depending on the use of the package options comments
and nocomments
(see above), or the \mglcomments
and \mglnocomments
commands (see bellow).
If many scripts with the same code are to be written, the repetitive code can be written inside this environment only once, then this code will be used automatically every time the ‘\mglplot’ command is used (see below). It takes one optional argument, which is a name to be associated to the corresponding contents of the environment; this name can be passed to the ‘\mglplot’ command to use the corresponding block of code automatically (see below).
The package also defines the following commands:
It takes one mandatory argument, which is MGL instructions separated by the symbol ‘:’ this argument can be more than one line long. It takes the same optional arguments as the ‘mgl’ environment, plus an additional argument setup, which indicates the name associated to a block of code inside a ‘mglsetup’ environment. The code inside the mandatory argument will be appended to the block of code specified, and the resulting code will be written to the general script.
An example of usage of ‘\mglplot’ command would be:
\begin{mglsetup} box '@{W9}' : axis \end{mglsetup} \begin{mglsetup}[2d] box : axis grid 'xy' ';k' \end{mglsetup} \begin{mglsetup}[3d] rotate 50 60 box : axis : grid 'xyz' ';k' \end{mglsetup} \begin{figure}[!ht] \centering \mglplot[scale=0.5]{new a 200 'sin(pi*x)' : plot a '2B'} \end{figure} \begin{figure}[!ht] \centering \mglplot[scale=0.5,setup=2d]{ fplot 'sin(pi*x)' '2B' : fplot 'cos(pi*x^2)' '2R' } \end{figure} \begin{figure}[!ht] \centering \mglplot[setup=3d]{fsurf 'sin(pi*x)+cos(pi*y)'} \end{figure}
This command takes the same optional arguments as the ‘mgl’ environment, and one mandatory argument, which is the name of a MGL script. This command will compile the corresponding script and include the resulting image. It is useful when you have a script outside the LaTeX document, and you want to include the image, but you don’t want to type the script again.
This is like ‘\mglgraphics’ but, instead of creating/including the corresponding image, it writes the contents of the MGL script to the LaTeX document, and numerates the lines.
This command can be used in the preamble of the document to specify a directory where LaTeX will save the MGL scripts and generate the corresponding images. This directory is also where ‘\mglgraphics’ and ‘\mglinclude’ will look for scripts.
Adjust the quality of the MGL graphics produced similarly to quality.
Activate/deactivate the creation of MGL scripts and images. Notice these commands have local behavior in the sense that their effect is from the point they are called on.
Make visible/invisible the contents of the mglcomment
environments. These commands have local effect too.
It just pretty prints the name of the package.
As an additional feature, when an image is not found or cannot be included, instead of issuing an error, mgltex
prints a box with the word ‘MGL image not found’ in the LaTeX document.
Next: MathGL core, Previous: MGL scripts, Up: Top [Contents][Index]
Возможности библиотеки MathGL довольно богаты – число только основных типов графиков превышает 50 видов. Кроме того, есть функции для обработки данных, настройки вида графика и пр. и пр. Тем не менее, я старался придерживаться единого стиля в порядке аргументов функций и способе их “настройки”. В основном все ниже сказанное относится к функциям рисования различных графиков.
Всего основных концепций (базисных идей) шесть:
SetQuality(MGL_DRAW_LMEM)
или quality 6
), так и векторные списки примитивов (по умолчанию). Дальнейшая судьба рисунков определяется пользователем: можно сохранить в файл, вывести на экран, создать анимацию/кино, дополнительно отредактировать и т.д. Такой подход обеспечивает высокую переносимость библиотеки – один и тот же программный код создаст в точности одинаковый рисунок на любой операционной системе. Кроме того, при таком подходе рисунки можно создавать непосредственно в консольной программе – графическое окно не нужно!
Кроме основных концепций я хотел бы остановиться на нескольких, как оказалось, нетривиальных моментах – способе указания положения графика, осей координат и строковых параметров линий, поверхностей, текста.
• Coordinate axes: | ||
• Color styles: | ||
• Line styles: | ||
• Color scheme: | ||
• Font styles: | ||
• Textual formulas: | ||
• Command options: | ||
• Interfaces: |
Next: Color styles, Up: General concepts [Contents][Index]
Представление системы координат в MathGL состоит из двух частей. Вначале координаты нормируются в диапазон изменения осей координат (see Axis settings). Если флаг SetCut()
установлен, то точки вне интервала отбрасываются, в противном случае, они проецируются на ограничивающий параллелепипед (см. Cutting). Кроме того, отбрасываются точки внутри границ, определенных переменными CutMinxCutMax и точки, для которых значение функции CutOff
() не равно нулю. После этого формулы перехода в криволинейную систему координат SetFunc()
применяются к каждой точке. Наконец, точка данных отображается с помощью одной из графических функций.
Диапазон изменения x, y, z-координат задается функциями SetRange()
или ranges. Точка пересечения осей координат задается функцией SetOrigin()
. При этом можно использовать NAN значения для автоматического выбора положения оси.
Кроме привычных осей x, y, z есть еще одна ось – цветовая шкала – ось c. Она используется при окрашивании поверхностей и задает границы изменения функции при окрашивании. Ее границы автоматически устанавливаются равными диапазону z-оси при вызове ranges. Возможно и ручное изменение границ цветового интервала посредством вызова SetRange('c', ...)
. Используйте colorbar для отображения цветовой шкалы.
Вид меток по осям определяется функцией SetTicks()
(see Ticks). Функция SetTuneTicks включает/выключает выделение общего множителя (большого или малого факторов в диапазоне) для меток осей координат. Наконец, если стандартный вид меток не устраивает пользователя, то их шаблон можно задать явно (можно использовать и ТеХ символы), воспользовавшись функцией SetTickTempl()
. Кроме того, в качестве меток можно вывести произвольный текст использовав функцию SetTicksVal()
.
Next: Line styles, Previous: Coordinate axes, Up: General concepts [Contents][Index]
Base colors are defined by one of symbol ‘wkrgbcymhRGBCYMHWlenupqLENUPQ’.
Символы цвета: ‘k’ – черный, ‘r’ – красный, ‘R’ – темно красный, ‘g’ – зеленый, ‘G’ – темно зеленый, ‘b’ – синий, ‘B’ – темно синий, ‘c’ – голубой, ‘C’ – темно голубой, ‘m’ – пурпурный, ‘M’ – темно пурпурный, ‘y’ – желтый, ‘Y’ – темно желтый (золотой), ‘h’ – серый, ‘H’ – темно серый, ‘w’ – белый, ‘W’ – светло серый, ‘l’ – сине-зеленый, ‘L’ – темно сине-зеленый, ‘e’ – желто-зеленый, ‘E’ – темно желто-зеленый, ‘n’ – небесно-синий, ‘N’ – темно небесно-синий, ‘u’ – сине-фиолетовый, ‘U’ – темно сине-фиолетовый, ‘p’ – фиолетовый, ‘P’ – темно фиолетовый, ‘q’ – оранжевый, ‘Q’ – темно оранжевый (коричневый).
В цветовой схеме можно использовать тональные (“подсвеченные”) цвета. Тональный цвет задается двумя символами в фигурных скобках ‘{cN}’: первый – обычный цвет, второй – его яркость цифрой. Цифра может быть в диапазоне ‘1’...‘9’. При этом ‘5’ соответствует нормальному цвету, ‘1’ – очень темная версия цвета (почти черный), ‘9’ – очень светлая версия цвета (почти белый). Например, цвета могут быть ‘{b2}’ ‘{b7}’ ‘{r7}’ и т.д.
Наконец, можно указать явно RGB или RGBA значения цвета, используя формат ‘{xRRGGBB}’ или ‘{xRRGGBBAA}’ соответственно. Например, ‘{xFF9966}’ даст цвет дыни.
Next: Color scheme, Previous: Color styles, Up: General concepts [Contents][Index]
Стиль линии задается строкой, которая может содержать символ цвета (‘wkrgbcymhRGBCYMHWlenupqLENUPQ’), тип пунктира (‘-|;:ji’ или пробел), ширину линии (‘0123456789’) и тип маркера (‘o+xsd.^v’ и модификатор ‘#’). Если пропущен цвет или тип пунктира, то используется значение по умолчанию с последним указанным цветом или значение из палитры (для see 1D plotting). По умолчанию палитры содержит следующие цвета: темно серый ‘H’, синий ‘b’, зеленый ‘g’, красный ‘r’, голубой ‘c’, пурпурный ‘m’, yellow ‘y’, серый ‘h’, сине-зеленый ‘l’, небесно-синий ‘n’, оранжевый ‘q’, желто-зеленый ‘e’, сине-фиолетовый ‘u’, фиолетовый ‘p’.
Тип пунктира: пробел – нет линии (для рисования только маркеров), ‘-’ – сплошная линия (■■■■■■■■■■■■■■■■), ‘|’ – длинный пунктир (■■■■■■■■□□□□□□□□), ‘;’ – пунктир (■■■■□□□□■■■■□□□□), ‘=’ – короткий пунктир (■■□□■■□□■■□□■■□□), ‘:’ – точки (■□□□■□□□■□□□■□□□), ‘j’ – пунктир с точками (■■■■■■■□□□□■□□□□), ‘i’ – мелкий пунктир с точками (■■■□□■□□■■■□□■□□), ‘{dNNNN}’ – заданный вручную стиль (для v.2.3 и поздних, например ‘{df090}’ для (■■■■□□□□■□□■□□□□)).
Типы маркеров: ‘o’ – окружность, ‘+’ – крест, ‘x’ – косой крест, ‘s’ – квадрат, ‘d’ - ромб, ‘.’ – точка, ‘^’ – треугольник вверх, ‘v’ – треугольник вниз, ‘<’ – треугольник влево, ‘>’ – треугольник вправо, ‘#*’ – знак Y, ‘#+’ – крест в квадрате, ‘#x’ – косой крест в квадрате, ‘#.’ – точка в окружности. Если в строке присутствует символ ‘#’, то используются символы с заполнением.
На конце и в начале линии можно выводить специальный символ (стрелку), если в строке указать один из символов: ‘A’ – стрелка наружу, ‘V’ – стрелка внутрь, ‘I’ – поперечная черта, ‘K’ – стрелка с чертой, ‘T’ – треугольник, ‘S’ – квадрат, ‘D’ – ромб, ‘O’ – круг, ‘X’ – косой крест, ‘_’ – нет стрелки (по умолчанию). При этом действует следующее правило: первый символ определяет стрелку на конце линии, второй символ – стрелку в начале линии. Например, ‘r-A’ – красная сплошная линия со стрелкой на конце, ‘b|AI’ – синий пунктир со стрелкой на конце и чертой вначале, ‘_O’ – линия с текущим стилем и кружком вначале. Эти стили действуют и при построении графиков (например, 1D plotting).
Next: Font styles, Previous: Line styles, Up: General concepts [Contents][Index]
Цветовая схема используется для определения цвета поверхностей, линий уровня и пр. Цветовая схема задается строкой s, которая содержит символы цвета (see Line styles) или символы ‘#:|’. Символ ‘#’ переключает рисование поверхности на сетчатое (для трехмерных поверхностей) или включает рисование сетки на поверхности. Символ ‘|’ отключает интерполяцию цвета в цветовой схеме. Это может быть полезно для “резких” цветов, например, при рисовании матриц. Если в строке встречается символ ‘:’, то он принудительно заканчивает разбор строки для стиля поверхности. После этого символа могут идти описание стиля текста или оси вращения кривой/линий уровня. Цветовая схема может содержать до 32 значений цвета.
При определении цвета по амплитуде (наиболее часто используется) окончательный цвет определяется путем линейной интерполяции массива цветов. Массив цветов формируется из цветов, указанных в строке спецификации. Аргумент – амплитуда, нормированная на диапазон изменения цвета (см. Axis settings). Например, строка из 4 символов ‘bcyr’ соответствует изменению цвета от синего (минимальное значение) через голубой и желтый (промежуточные значения) к красному (максимальное значение). Строка ‘kw’ соответствует изменению цвета от черного (минимальное значение) к белому (максимальное значение). Строка из одного символа (например, ‘g’) соответствует однотонному цвету (в данному случае зеленому).
Специальная двуосная цветовая схема (как в графике map) задается символом ‘%’. В ней второе направление (прозрачность) используется как вторая координата для цвета. При этом можно указать до 4 цветов для углов: {c1,a1}, {c2,a1}, {c1,a2}, {c2,a2}. Здесь диапазоны цвета и прозрачности равны {c1,c2} и {a1,a2}. Если указано меньше 4 цветов, то черный используется для угла {c1,a1}. Если задано только 2 цвета, то их сумма используется для угла {c2,a2}.
Есть несколько полезных цветовых схем. Строка ‘kw’ дает обычную серую (черно-белую) схему, когда большие значения светлее. Строка ‘wk’ представляет обратную серую схему, когда большие значения темнее. Строки ‘kRryw’, ‘kGgw’, ‘kBbcw’ представляют собой хорошо известные схемы hot, summer и winter. Строки ‘BbwrR’ и ‘bBkRr’ позволяют рисовать двухцветные фигуры на белом или черном фоне, когда отрицательные значения показаны синим цветом, а положительные – красным. Строка ‘BbcyrR’ дает цветовую схему, близкую к хорошо известной схеме jet.
Для более точно раскрашивания поверхностей можно изменить равномерное (по умолчанию) положение цветов в цветовой схеме. Формат следующий: ‘{CN,pos}’, ‘{CN,pos}’ или ‘{xRRGGBB,pos}’. Здесь значение pos положения цвета должно быть в диапазоне [0, 1]. Отмечу, что альтернативным механизмом тонкой настройки цветовой схемы может служить использование формул для цветовой координаты (см. Curved coordinates).
При определении цвета по положению точки в пространстве (используется в map) окончательный цвет определяется по формуле c=x*c[1] + y*c[2]. Здесь c[1], c[2] – первые три цвета в цветовом массиве; x, y – координаты точки, нормированные в диапазон изменения осей координат.
Дополнительно, MathGL может наложить маску при закраске граней для создания растрового изображения. Тип маски задается одним из символов ‘-+=;oOsS~<>jdD*^’ в цветовой схеме. Маску можно повернуть на произвольный угол командой mask или на один из улов +45, -45 или 90 градусов, используя символы ‘\/I’ соответственно. Примеры масок по умолчанию показаны на рисунке ниже.
Однако, вы можете задать собственную маску (как матрицу 8*8) для любого из этих символов, используя второй аргумент команды mask. Например, маска на правом нижнем подрисунке получается кодом
mask '+' 'ff00182424f80000':dens a '3+'
или использовать явное задание маски (для v.2.3 и более поздних)
dens a '3{s00ff00182424f800}'
Next: Textual formulas, Previous: Color scheme, Up: General concepts [Contents][Index]
Стиль текста задается строкой, которая может содержать цвет текста ‘wkrgbcymhRGBCYMHW’ (см. Color styles), а также тип шрифта (‘ribwou’) и/или выравнивания (‘LRC’) после символа ‘:’. Например, ‘r:iCb’ соответствует жирному (‘b’) курсиву (‘i’) с выравниванием по центру (‘C’ красного цвета (‘r’). Начиная с MathGL версии 2.3, вы можете использовать не только один цвет для всего текста, но и задать цветовой градиент для выводимой строки (см. Color scheme).
Начертания шрифта: ‘r’ – прямой шрифт, ‘i’ – курсив, ‘b’ – жирный. По умолчанию используется прямой шрифт. Типы выравнивания текста: ‘L’ – по левому краю (по умолчанию), ‘C’ – по центру, ‘R’ – по правому краю, ‘T’ – под текстом, ‘V’ – по центру вертикально. Дополнительные эффекты шрифта: ‘w’ – контурный, ‘o’ – надчеркнутый, ‘u’ – подчеркнутый.
Синтаксический разбор LaTeX-их команд по умолчанию включен. Это команды смены стиля текста (например, \b для жирного текста): \a или \overline – надчеркивание, \b или \textbf – жирный, \i или \textit – курсив, \r или \textrm – прямой (отменяет стили жирного и курсива), \u или \underline – подчеркнутый, \w или \wire – контурный, \big – большего размера, @ – меньшего размера. Нижний и верхний индексы задаются символами ‘_’ и ‘^’. При этом изменение стиля применяется только к следующему символу или к символам в фигурных скобках {}, которые понимаются как единый блок. Например, сравните строки ‘sin (x^{2^3})’ и ‘sin (x^2^3)’. Можно также менять цвет текста внутри строки с помощью команд #? или \color?, где ‘?’ – символ цвета (see Line styles). Например, слова ‘Blue’ и ‘red’ будут окрашены в соответствующий цвет в строке ‘#b{Blue} and \colorr{red} text’. Большинство функций понимает символ новой строки ‘\n’ и позволяет выводить много строчный текст. Наконец, можно использовать символы с произвольным UTF кодом с помощью команды \utf0x????
. Например, \utf0x3b1
даст символ
α.
Распознаются также большинство символов TeX и AMSTeX, команды смены стиля текста (\textrm, \textbf, \textit, \textsc, \overline, \underline), акценты (\hat, \tilde, \dot, \ddot, \acute, \check, \grave, \bar, \breve) и корни (\sqrt, \sqrt3, \sqrt4). Полный список содержит около 2000 символов. Отмечу, что первый пробел (пробел, табуляция и пр.) после команды игнорируется, а все остальные пробелы печатаются обычным образом. Например, следующие строки дают одинаковый результат \tilde a: ‘\tilde{a}’; ‘\tilde a’; ‘\tilde{}a’.
В частности, распознаются греческие буквы: α – \alpha, β – \beta, γ – \gamma, δ – \delta, ε – \epsilon, η – \eta, ι – \iota, χ – \chi, κ – \kappa, λ – \lambda, μ – \mu, ν – \nu, o – \o, ω – \omega, ϕ – \phi, π – \pi, ψ – \psi, ρ – \rho, σ – \sigma, θ – \theta, τ – \tau, υ – \upsilon, ξ – \xi, ζ – \zeta, ς – \varsigma, ɛ – \varepsilon, ϑ – \vartheta, φ – \varphi, ϰ – \varkappa; A – \Alpha, B – \Beta, Γ – \Gamma, Δ – \Delta, E – \Epsilon, H – \Eta, I – \Iota, C – \Chi, K – \Kappa, Λ – \Lambda, M – \Mu, N – \Nu, O – \O, Ω – \Omega, Φ – \Phi, Π – \Pi, Ψ – \Psi, R – \Rho, Σ – \Sigma, Θ – \Theta, T – \Tau, Υ – \Upsilon, Ξ – \Xi, Z – \Zeta.Еще примеры наиболее общеупотребительных TeX-их символов: ∠ – \angle, ⋅ – \cdot, ♣ – \clubsuit, ✓ – \checkmark, ∪ – \cup, ∩ – \cap, ♢ – \diamondsuit, ◇ – \diamond, ÷ – \div, ↓ – \downarrow, † – \dag, ‡ – \ddag, ≡ – \equiv, ∃ – \exists, ⌢ – \frown, ♭ – \flat, ≥ – \ge, ≥ – \geq, ≧ – \geqq, ← – \gets, ♡ – \heartsuit, ∞ – \infty, ∫ – \int, \Int, ℑ – \Im, ♢ – \lozenge, ⟨ – \langle, ≤ – \le, ≤ – \leq, ≦ – \leqq, ← – \leftarrow, ∓ – \mp, ∇ – \nabla, ≠ – \ne, ≠ – \neq, ♮ – \natural, ∮ – \oint, ⊙ – \odot, ⊕ – \oplus, ∂ – \partial, ∥ – \parallel, ⊥ –\perp, ± – \pm, ∝ – \propto, ∏ – \prod, ℜ – \Re, → – \rightarrow, ⟩ – \rangle, ♠ – \spadesuit, ~ – \sim, ⌣ – \smile, ⊂ – \subset, ⊃ – \supset, √ – \sqrt or \surd, § – \S, ♯ – \sharp, ∑ – \sum, × – \times, → – \to, ∴ – \therefore, ↑ – \uparrow, ℘ – \wp.
Размер текста может быть задан явно (если size>0) или относительно базового размера шрифта для рисунка |size|*FontSize при size<0. Значение size=0 указывает, что соответствующая строка выводиться не будет. Базовый размер шрифта измеряется во внутренних единицах. Специальные функции SetFontSizePT(), SetFontSizeCM(), SetFontSizeIN()
позволяют задавать его в более “привычных” единицах.
Next: Command options, Previous: Font styles, Up: General concepts [Contents][Index]
MathGL имеет быстрый парсер текстовых формул , понимающий большое число функций и операций. Базовые операции: ‘+’ – сложение, ‘-’ – вычитание, ‘*’ – умножение, ‘/’ – деление, ‘^’ – возведение в целосичленную степень. Также есть логические операции: ‘<’ – истина если if x<y, ‘>’ – истина если x>y, ‘=’ – истина если x=y, ‘&’ – истина если x и y оба не равны нулю, ‘|’ – истина если x или y не нуль. Логические операции имеют наинизший приоритет и возвращают 1 если истина или 0 если ложно.
Базовые функции: ‘sqrt(x)’ – квадратный корень из x, ‘pow(x,y)’ – x в степени y, ‘ln(x)’ – натуральный логарифм x, ‘lg(x)’ – десятичный логарифм x, ‘log(a,x)’ – логарифм по основанию a от x, ‘abs(x)’ – модуль x, ‘sign(x)’ – знак x, ‘mod(x,y)’ – остаток от деления x на y, ‘step(x)’ – ступенчатая функция, ‘int(x)’ – целая часть x, ‘rnd’ – случайное число, ‘random(x)’ – матрица случайный чисел размером как x, ‘pi’ – число π = 3.1415926…, inf=∞
Функции для работы с комплексными числами ‘real(x)’, ‘imag(x)’, ‘abs(x)’, ‘arg(x)’, ‘conj(x)’.
Тригонометрические функции: ‘sin(x)’, ‘cos(x)’, ‘tan(x)’ (или ‘tg(x)’). Обратные тригонометрические функции: ‘asin(x)’, ‘acos(x)’, ‘atan(x)’. Гиперболические функции: ‘sinh(x)’ (или ‘sh(x)’), ‘cosh(x)’ (или ‘ch(x)’), ‘tanh(x)’ (или ‘th(x)’). Обратные гиперболические функции: ‘asinh(x)’, ‘acosh(x)’, ‘atanh(x)’.
Специальные функции: ‘gamma(x)’ – гамма функция Γ(x) = ∫0∞ tx-1 exp(-t) dt, ‘gamma_inc(x,y)’ – неполная гамма функция Γ(x,y) = ∫y∞ tx-1 exp(-t) dt, ‘psi(x)’ – дигамма функция ψ(x) = Γ′(x)/Γ(x) для x≠0, ‘ai(x)’ – Эйри функция Ai(x), ‘bi(x)’ – Эйри функция Bi(x), ‘cl(x)’ – функция Клаузена, ‘li2(x)’ (или ‘dilog(x)’) – дилогарифм Li2(x) = -ℜ∫0xds log(1-s)/s, ‘sinc(x)’ – функция sinc(x) = sin(πx)/(πx) для любых x, ‘zeta(x)’ – зета функция Римана ζ(s) = ∑k=1∞k-s для s≠1, ‘eta(x)’ – эта функция η(s) = (1 - 21-s)ζ(s) для произвольного s, ‘lp(l,x)’ – полином Лежандра Pl(x), (|x|≤1, l≥0), ‘w0(x)’, ‘w1(x)’ – функции Ламберта W. Функции W(x) определены как решение уравнения: W exp(W) = x.
Экспоненциальные интегралы: ‘ci(x)’ – cos-интеграл Ci(x) = ∫0xdt cos(t)/t, ‘si(x)’ – sin-интеграл Si(x) = ∫0xdt sin(t)/t, ‘erf(x)’ – функция ошибки erf(x) = (2/√π) ∫0xdt exp(-t2) , ‘ei(x)’ – интеграл Ei(x) = -PV(∫-x∞dt exp(-t)/t) (где PV обозначает главное значение), ‘e1(x)’ – интеграл E1(x) = ℜ∫1∞dt exp(-xt)/t, ‘e2(x)’ – интеграл E2(x) = ℜ∫1∞dt exp(-xt)/t2, ‘ei3(x)’ – интеграл Ei3(x) = ∫0xdt exp(-t3) для x≥0.
Функции Бесселя: ‘j(nu,x)’ – функция Бесселя первого рода, ‘y(nu,x)’ – функция Бесселя второго рода, ‘i(nu,x)’ – модифицированная функция Бесселя первого рода, ‘k(nu,x)’ – модифицированная функция Бесселя второго рода.
Эллиптические интегралы: ‘ee(k)’ – полный эллиптический интеграл E(k) = E(π/2,k), ‘ek(k)’ – полный эллиптический интеграл K(k) = F(π/2,k), ‘e(phi,k)’ – эллиптический интеграл E(φ,k) = ∫0φdt √(1 - k2sin2(t)), ‘f(phi,k)’ – эллиптический интеграл F(φ,k) = ∫0φdt 1/√(1 - k2sin2(t))
Функции Якоби: ‘sn(u,m)’, ‘cn(u,m)’, ‘dn(u,m)’, ‘sc(u,m)’, ‘sd(u,m)’, ‘ns(u,m)’, ‘cs(u,m)’, ‘cd(u,m)’, ‘nc(u,m)’, ‘ds(u,m)’, ‘dc(u,m)’, ‘nd(u,m)’.
Некоторые из функций могут быть недоступны если не была включена поддержка GSL при компиляции библиотеки MathGL.
При разборе формул нет различия между верхним и нижним регистром. Если аргумент лежит вне области определения функции, то возвращается NaN.
Next: Interfaces, Previous: Textual formulas, Up: General concepts [Contents][Index]
Опции команд позволяют легко настроить вид отдельного графика не меняя глобальных настроек для все рисунка. Каждая опция отделяется от предыдущей символом ‘;’. Опции работают так, что запоминают текущие настройки рисунка, применяют собственные настройки, выполняют команду и возвращают глобальные настройки обратно. Поэтому использование опций для команд обработки данных или настройки графика бесполезно.
Наиболее часто используемые опции – xrange, yrange, zrange
, устанавливают границы изменения осей координат (и тем самым автоматических массивов). Например, команда Plot(y,"","xrange 0.1 0.9");
или plot y; xrange 0.1 0.9
построит кривую с x-координатой равно распределенной в интервале 0.1 ... 0.9, а не вдоль текущей оси x. См. Using options, для примеров кода и графика.
val
Задает величину прозрачности поверхности. Значение должно быть в диапазоне [0, 1]. См. также alphadef
val1 val2
Задает границы изменения координаты x. См. также xrange
val1 val2
Задает границы изменения координаты y. См. также yrange
val1 val2
Задает границы изменения координаты z. См. также zrange
val
Задает обрезание точек за пределами осей координат. См. также cut.
val
Задает ориентировочное число линий, стрелок, ячеек и пр. См. также meshnum
Добавляет строку ’txt’ во внутренний массив записей легенды. Стиль линии и маркера аргумента последней вызванной команды построения 1D plotting. См. также legend
val
Задает значение, которое будет использовано как дополнительный числовой параметр при построении графика.
Previous: Command options, Up: General concepts [Contents][Index]
Вы можете использовать класс mglParse
для выполнения MGL скриптов из других языков программирования.
Next: Data processing, Previous: General concepts, Up: Top [Contents][Index]
Эта глава посвящена описанию множества команд построения графиков для 1D, 2D и 3D массивов данных. Сюда включены также команды настройки графика, вывода текста и примитивов, рисования осей координат и др. Дополнительную информацию о цвете, шрифтах, стилях линий и формулах можно найти в General concepts.
Некоторые возможности MathGL доступны только в новых версиях библиотеки. Для проверки текущей версии MathGL можно использовать следующую функцию.
Возвращает нулевое значение если версия MathGL подходит для требуемой в ver, т.е. если номер основной версии совпадает и "подверсия" больше или равна указанной в ver.
• Constructor: | ||
• Graphics setup: | ||
• Axis settings: | ||
• Subplots and rotation: | ||
• Export picture: | ||
• Background: | ||
• Primitives: | ||
• Text printing: | ||
• Axis and Colorbar: | ||
• Legend: | ||
• 1D plotting: | ||
• 2D plotting: | ||
• 3D plotting: | ||
• Dual plotting: | ||
• Vector fields: | ||
• Other plotting: | ||
• Nonlinear fitting: | ||
• Data manipulation: |
Next: Graphics setup, Up: MathGL core [Contents][Index]
MGL не требует создания данного типа объектов.
Next: Axis settings, Previous: Constructor, Up: MathGL core [Contents][Index]
Функции и переменные в этой группе влияют на вид всего рисунка. Соответственно они должны располагаться перед вызовом функций непосредственно рисующих графики.
Устанавливает все настройки по умолчанию и очищает рисунок.
• Transparency: | ||
• Lighting: | ||
• Fog: | ||
• Default sizes: | ||
• Cutting: | ||
• Font settings: | ||
• Palette and colors: | ||
• Masks: | ||
• Error handling: | ||
• Stop drawing: |
Next: Lighting, Up: Graphics setup [Contents][Index]
Эти функции и переменные настраивают тип и степень прозрачности поверхностей. Главной является функция alpha, которая включает/выключает прозрачность для всего графика. Функция alphadef устанавливает величину alpha-канала по умолчанию. Наконец, функция transptype задает тип прозрачности. См. Transparency and lighting, для примеров кода и графика.
[val=on]
Включает/выключает прозрачность и возвращает свое предыдущее состояние. По умолчанию прозрачность выключена. Функция включает прозрачность для всего рисунка.
val
Задает значение прозрачности по умолчанию для всех графиков. Значение по умолчанию 0.5.
val
Задает тип прозрачности. Обычная прозрачность (‘0’) – "закрытые" объекты видны меньше чем закрывающие. Этот режим некорректно отображается в OpenGL (mglGraphGL) для нескольких перекрывающихся поверхностей. "Стеклянная" прозрачность (‘1’) – закрытые и закрывающие объекты единообразно ослабляют интенсивность света (по RGB каналам). "Ламповая" прозрачность (‘2’) – закрытые и закрывающие объекты являются источниками дополнительного освещения (рекомендую установить SetAlphaDef(0.3)
или меньше в этом случае). См. Types of transparency, для примеров кода и графика.
Next: Fog, Previous: Transparency, Up: Graphics setup [Contents][Index]
Эти функции настраивают освещение графика. Главная функция light включает/выключает освещение графиков построенных после ее вызова (в OpenGL работает сразу для всего рисунка). MathGL поддерживает до 10 независимых источников света. Но в режиме OpenGL можно использовать только первые 8 из них. Положение, цвет, яркость каждого источника света можно задавать по отдельности. По умолчанию включен только первый (с порядковым номером 0
) источник света белого цвета, расположенный сверху. См. Lighting sample, для примеров кода и графика.
[val=on]
Включает/выключает освещение графика и возвращает предыдущее состояние. По умолчанию освещение выключено.
num
val
Включает/выключает n-ый источник света.
num xdir ydir zdir
['col'='w' br=0.5
]num xdir ydir zdir xpos ypos zpos
['col'='w' br=0.5
]Добавляет источник света с номером n в положение p с цветом c и яркостью bright, которая должна быть в диапазоне [0,1]. Если указано положение источника r и оно не NAN, то источник считается локальным, иначе источник полагается бесконечно удалённым (для более быстрого рисования).
val
Задает яркость диффузного освещения (только для локальных источников света).
val
Задает яркость рассеянного освещения. Значение должно быть в диапазоне [0,1].
val
Задает привязку настроек освещения к inplot/subplot. Отмечу, что OpenGL и некоторые выходные форматы не поддерживают эту возможность.
Next: Default sizes, Previous: Lighting, Up: Graphics setup [Contents][Index]
val [dz=0.25]
Имитирует туман на графике. Туман начинается на относительном расстоянии dz от точки обзора и его плотность растет экспоненциально вглубь по закону ~ 1-exp(-d*z). Здесь z – нормализованная на 1 глубина графика. Если d=0
то туман отсутствует. См. Adding fog, для примеров кода и графика.
Next: Cutting, Previous: Fog, Up: Graphics setup [Contents][Index]
Эти функции задают величины большинства параметров графика, включая размеры маркеров, стрелок, толщину линий и т.д. Как и любые другие настройки, они подействуют только на графики созданные после изменения настроек.
val
Задает относительный размер прямоугольников в bars, barh, boxplot, candle. Значение по умолчанию 0.7
.
val
Задает размер маркеров для 1D plotting. Значение по умолчанию 1
.
val
Задает размер стрелок для 1D plotting, линий и кривых (см. Primitives). Значение по умолчанию 1
.
val
Задает ориентировочное число линий в mesh, fall и число стрелок (штрихов) в vect, dew и число ячеек в cloud. По умолчанию (=0) рисуются все линии, стрелки, ячейки.
val
Задает ориентировочное число видимых граней. Может быть использована для ускорения рисования за счет более грубого рисунка. По умолчанию (=0) рисуются все грани.
Задает имя графика для сохранения в файл (например, в окне FLTK).
val
Изменяет размытие около линий и текста (по умолчанию 1). Для val>1 текст и линии более резкие. Для val<1 текст и линии более размытые.
Next: Font settings, Previous: Default sizes, Up: Graphics setup [Contents][Index]
Эти функции задают условия когда точка будет исключена (вырезана) из рисования. Замечу, что все точки со значением(-ями) NAN по одной из координат или амплитуде автоматически исключаются из рисования. См. Cutting sample, для примеров кода и графика.
val
Задает обрезание точек за пределами осей координат. Если true
то такие точки исключаются из рисования (это по умолчанию) иначе они проецируются на ограничивающий прямоугольник.
x1 y1 z1 x2 y2 z2
Задает границы параллелепипеда внутри которого точки не рисуются. Если границы одинаковы (переменные равны), то параллелепипеда считается пустым.
Задает условие обрезания по формуле cond. Это условие исключает точки из рисования если результат вычисления формулы не равен нулю. Установите аргумент ""
для выключения условия обрезания.
Next: Palette and colors, Previous: Cutting, Up: Graphics setup [Contents][Index]
val=6
]Задает стиль и размер шрифта. Вначале используется ‘:rC’ – прямой шрифт с выравниванием по центру. По умолчанию размер подписей оси координат в 1.4 раза больше. См. также см. Font styles.
val
Включает/выключает вращение меток и подписей осей координат вдоль оси.
Загружает начертание шрифта из файла path/name. Пустая строка загрузит шрифт по умолчанию.
Next: Masks, Previous: Font settings, Up: Graphics setup [Contents][Index]
Задает палитру как последовательность цветов. Значение по умолчанию "Hbgrcmyhlnqeup"
, что соответствует цветам: темно серый ‘H’, синий ‘b’, зелёный ‘g’, красный ‘r’, голубой ‘c’, малиновый ‘m’, жёлтый ‘y’, серый ‘h’, сине-зелёный ‘l’, небесно-голубой ‘n’, оранжевый ‘q’, желто-зелёный ‘e’, сине-фиолетовый ‘u’, фиолетовый ‘p’. Палитра в основном используется в 1D графиках (см. 1D plotting) для кривых с неопределённым стилем линии. Внутренний счетчик цвета будет сброшен при любом изменении палитры, включая скрытые (например, функциями box или axis).
val
Включает/выключает вывод графика в оттенках серого.
Next: Error handling, Previous: Palette and colors, Up: Graphics setup [Contents][Index]
Задает новую матрицу hex размером 8*8 для маски с заданным id. Изменения действуют глобально для всех последующих использований данного id. Значения по умолчанию (см. Color scheme): ‘-’ – 000000FF00000000, ‘+’ – 080808FF08080808, ‘=’ – 0000FF00FF000000, ‘;’ – 0000007700000000, ‘o’ – 0000182424180000, ‘O’ – 0000183C3C180000, ‘s’ – 00003C24243C0000, ‘S’ – 00003C3C3C3C0000, ‘~’ – 0000060990600000, ‘<’ – 0060584658600000, ‘>’ – 00061A621A060000, ‘j’ – 0000005F00000000, ‘d’ – 0008142214080000, ‘D’ – 00081C3E1C080000, ‘*’ – 8142241818244281, ‘^’ – 0000001824420000.
Задает угол поворота маски в градусах. Отмечу, что символы ‘\’, ‘/’, ‘I’ в цветовой схеме задают угол поворота в 45, -45 и 90 градусов соответственно.
Next: Stop drawing, Previous: Masks, Up: Graphics setup [Contents][Index]
Все сообщения будут выведены автоматически в специальном окне или в консоли.
Previous: Error handling, Up: Graphics setup [Contents][Index]
Вы можете использовать команду stop или соответствующую кнопку панели инструментов для остановки рисования и выполнения скрипта.
Next: Subplots and rotation, Previous: Graphics setup, Up: MathGL core [Contents][Index]
Эти функции управляет видом и масштабом осей координат. Перед построением для каждой точки выполняются 3 преобразования: сначала определяется возможность рисования точки (см. Cutting), далее применяются формулы перехода к криволинейным координатам и наконец точка отображается. Отмечу, что MathGL выдает предупреждение если масштабы осей координат лежат вне области определения формул преобразования координат.
• Ranges (bounding box): | ||
• Curved coordinates: | ||
• Ticks: |
Next: Curved coordinates, Up: Axis settings [Contents][Index]
v1 v2
[add=off
]v1 v2
[add=off
]v1 v2
[add=off
]v1 v2
[add=off
]Задает диапазон изменения ‘x’-,‘y’-,‘z’-,‘c’-координат. Если одно из значений равно NAN
, то оно игнорируется. Параметр add=on
указывает добавлять новый диапазон к существующему (не заменять его). См. также ranges.
add=off
]add=off
]add=off
]add=off
]Задает диапазон изменения ‘x’-,‘y’-,‘z’-,‘c’-координат как минимальное и максимальное значение массива dat. Параметр add=on
указывает добавлять новый диапазон к существующему (не заменять его).
x1 x2 y1 y2 [z1=0 z2=0]
Задает диапазон изменения координат. Если минимальное и максимальное значение координаты равны, то они игнорируются по данному направлению. Также устанавливает размер цветовой шкалы, аналогично команде crange z1 z2
. Начальные диапазоны равны [-1, 1].
x0 y0 [z0=nan]
Задает центр пересечения осей координат. Если одно из значений равно NAN, то MathGL попытается выбрать оптимальное положение осей координат по этому направлению.
x1 x2
x1 y1 x2 y2
x1 y1 z1 x2 y2 z2
x1 y1 z1 c1 x2 y2 z2 c2
Дополнительно расширяет диапазон осей координат, задаваемый функциями SetRange
или SetRanges
, в соответствии с формулами min += (max-min)*p1 и max += (max-min)*p1 (или min *= (max/min)^p1 и max *= (max/min)^p1 для "логарифмических" диапазонов, когда inf>max/min>100 или 0<max/min<0.01). Начальные значения [0, 1]. Внимание! эти настройки не могут быть переписаны никакими другими функциями, включая DefaultPlotParam()
.
Next: Ticks, Previous: Ranges (bounding box), Up: Axis settings [Contents][Index]
Задает формулы перехода к криволинейным координатам. Каждая строка является математическим выражением, зависящим от старых координат ‘x’, ‘y’, ‘z’ и ‘a’ или ‘c’ для цветовой шкалы. Например, для цилиндрических координат будет SetFunc("x*cos(y)", "x*sin(y)", "z");
. Для удаления формул соответствующий параметр должен быть пустым или NULL
. Использование формул преобразования слегка замедляет программу. Параметр EqA задает аналогичную формулу для цветовой шкалы. See Textual formulas.
how
Устанавливает одну из предопределенных систем криволинейных координат в зависимости от параметра how: mglCartesian=0
– декартова система (нет преобразования координат, наиболее быстрая); mglPolar=1
– полярные координаты x_n=x*cos(y),y_n=x*sin(y), z_n=z; mglSpherical=2
– сферические координаты x_n=x*sin(y)*cos(z), y_n=x*sin(y)*sin(z), z_n=x*cos(y); mglParabolic=3
– параболические координаты x_n=x*y, y_n=(x*x-y*y)/2, z_n=z; mglParaboloidal=4
– Paraboloidal coordinates x_n=(x*x-y*y)*cos(z)/2, y_n=(x*x-y*y)*sin(z)/2, z_n=x*y; mglOblate=5
– Oblate coordinates x_n=cosh(x)*cos(y)*cos(z), y_n=cosh(x)*cos(y)*sin(z), z_n=sinh(x)*sin(y); mglProlate=6
– Prolate coordinates x_n=sinh(x)*sin(y)*cos(z), y_n=sinh(x)*sin(y)*sin(z), z_n=cosh(x)*cos(y); mglElliptic=7
– эллиптические координаты x_n=cosh(x)*cos(y), y_n=sinh(x)*sin(y), z_n=z; mglToroidal=8
– тороидальные координаты x_n=sinh(x)*cos(z)/(cosh(x)-cos(y)), y_n=sinh(x)*sin(z)/(cosh(x)-cos(y)), z_n=sin(y)/(cosh(x)-cos(y)); mglBispherical=9
– бисферические координаты x_n=sin(y)*cos(z)/(cosh(x)-cos(y)), y_n=sin(y)*sin(z)/(cosh(x)-cos(y)), z_n=sinh(x)/(cosh(x)-cos(y)); mglBipolar=10
– биполярные координаты x_n=sinh(x)/(cosh(x)-cos(y)), y_n=sin(y)/(cosh(x)-cos(y)), z_n=z; mglLogLog=11
– log-log координаты x_n=lg(x), y_n=lg(y), z_n=lg(z); mglLogX=12
– log-x координаты x_n=lg(x), y_n=y, z_n=z; mglLogY=13
– log-y координаты x_n=x, y_n=lg(y), z_n=z.
val
Задает рисование треугольных (Ternary, tern=1
), пирамидальных (Quaternary, tern=2
) осей координат и проекций осей координат (tern=4,5,6
).
Ternary – специальный тип графика для 3 зависимых координат (компонент) a, b, c таких, что a+b+c=1. MathGL использует только 2 независимые координаты a=x и b=y поскольку их достаточно для построения всех графиков. При этом третья координата z является независимым параметром для построения линий уровня, поверхностей и т.д.
Соответственно Quaternary координаты – 4 зависимые координаты a, b, c и d, такие что a+b+c+d=1. MathGL использует только 2 независимые координаты a=x, b=y и d=z поскольку их достаточно для построения всех графиков.
Проекции строятся если к переменной tern добавить число 4
. Так что tern=4
нарисует проекции в декартовых координатах, tern=5
нарисует проекции в треугольных координатах, tern=6
нарисует проекции в пирамидальных координатах. Если добавить 8
вместо 4
, то текст не будет выводиться на проекциях.
Используйте Ternary(0)
для возвращения к привычным координатам. См. Ternary axis, для примеров кода и графика. См. Axis projection, для примеров кода и графика.
Previous: Curved coordinates, Up: Axis settings [Contents][Index]
Автоматически задает шаг меток осей, число подметок и начальное положение меток для осей координат dir в виде наиболее удобном для человека. Также задает SetTuneTicks(true)
. Обычно не требуется вызывать эту функцию кроме случая возвращения настроек по умолчанию.
val [sub=0 org=nan]
val [sub=0 org=nan]
val [sub=0 org=nan]
val [sub=0 org=nan]
Задает шаг меток осей d, число подметок ns и начальное положение меток org для оси вдоль направления dir (используйте ’c’ для меток colorbar). Переменная d задает шаг меток (если положительна) или их число на оси (если отрицательна). Нулевое значение задает автоматическую расстановку меток. Если org=NAN
, то используется значение из переменной Org. Параметр fact задает текст, которые будет напечатан после метки оси (например, "\pi" для d=M_PI).
val1
'lbl1' [val2
'lbl2' ...]val1
'lbl1' [val2
'lbl2' ...]val1
'lbl1' [val2
'lbl2' ...]add=off
]add=off
]add=off
]Задает явное положение val и подписи lbl для меток вдоль оси dir. Если массив val не указан, то используются значения равно распределённые в диапазоне осей координат. Метки разделяются символом ‘\n’. Используйте SetTicks()
для восстановления автоматических меток.
Задает шаблон templ для меток вдоль x-,y-,z-оси или colorbar. Шаблон может содержать и символы TeX. Если templ=""
, то используется шаблон по умолчанию (в простейшем случае ‘%.2g’). Если шаблон начинается с символа ‘&’, то будет использовано целое long
вместо типа double
. Установка шаблона выключает автоматическое улучшение вида меток.
dv
'tmpl']Задает метки времени с шагом val и шаблоном templ для меток вдоль x-,y-,z-оси или colorbar. Шаблон может содержать и символы TeX. Формат шаблона templ такой же как http://www.manpagez.com/man/3/strftime/. Наиболее употребительные варианты: ‘%X’ для национального представления времени, ‘%x’ для национального представления даты, ‘%Y’ для года с цифрами столетия. Если val=0 и/или templ="", то используется автоматическая расстановка меток и/или выбор шаблона. Вы можете использовать функцию mgl_get_time
() для получения числа секунд с 1970 года до указанной даты/времени. Отмечу, что MS Visual Studio не может обрабатывать даты до 1970.
val
[pos=1.15
]Включает/выключает улучшение вида меток осей путем вынесения общего множителя (для маленьких, типа 0.001...0.002, или больших, типа 1000...2000, значений координат) или общей компоненты (для узкого диапазона, типа 0.999...1.000). Также задает положение pos общего множителя на оси: =0 около минимального значения, =1 около максимального значения.
dx [dy=0 dz=0 dc=0]
Задает значение дополнительного сдвига меток осей координат.
val
Разрешает/запрещает рисование меток в точке пересечения осей координат. В C/Fortran следует использовать mgl_set_flag(gr,val, MGL_NO_ORIGIN);
.
val
[stt=1
]Задает относительную длину меток осей координат. Значение по умолчанию 0.1
. Параметр stt>0 задает относительную длину подметок, которые в sqrt(1+stt)
раз меньше.
Задает стиль осей (stl), меток (tck) и подметок (sub) осей координат. Если stl пустая или ноль, то используется стиль по умолчанию (‘k’ или ‘w’ в зависимости от типа прозрачности). Если tck, sub пустая или ноль, то используется стиль осей (т.е. stl).
Next: Export picture, Previous: Axis settings, Up: MathGL core [Contents][Index]
Эти функции контролируют где и как график будет расположен. Существует определенный порядок вызова этих функций для лучшего вида графика. Вначале должны вызываться функции subplot, multiplot или inplot для указания местоположения вывода. После них – функции вращения rotate, shear и aspect. И наконец любые другие функции для рисования графика. Вместо вращения графика можно вызвать функцию columnplot, gridplot, stickplot, shearplot или относительную inplot для расположения графиков в столбец одного над другим без зазора между осями. См. Subplots, для примеров кода и графика.
nx ny m ['stl'='<>_^' dx=0 dy=0]
Помещает последующий вывод в m-ую ячейку сетки размером nx*ny от всего рисунка. Функция сбрасывает матрицу трансформации (повороты и сжатие графика) и должна вызываться первой для создания "подграфика". С эстетической точки зрения не рекомендуется вызывать эту функцию с различными (или не кратными) размерами сетки. Место для осей/colorbar резервируется только если строка stl содержит: ‘L’ или ‘<’ – с левого края, ‘R’ или ‘>’ – с правого края, ‘A’ или ‘^’ – с верхнего края, ‘U’ или ‘_’ – с нижнего края. Если строка stl содержит ‘#’, то оси координат будут занимать все доступное пространство (место резервироваться не будет). Ячейка может быть дополнительно сдвинута относительно своего обычного положения на относительный размер dx, dy. Отмечу, что colorbar может находиться за пределами рисунка если выбран пустой стиль ‘’.
nx ny m dx dy
['style'='<>_^']Помещает последующий вывод в прямоугольник из dx*dy ячеек, начиная с m-ой ячейки, сетки размером nx*ny от всего рисунка. Функция сбрасывает матрицу трансформации (повороты и сжатие графика) и должна вызываться первой для создания "подграфика". Место для осей/colorbar резервируется если строка stl содержит: ‘L’ или ‘<’ – с левого края, ‘R’ или ‘>’ – с правого края, ‘A’ или ‘^’ – с верхнего края, ‘U’ или ‘_’ – с нижнего края.
x1 x2 y1 y2 [rel=on]
Помещает последующий вывод в прямоугольную область [x1, x2]*[y1, y2] (исходный размер [0,1]*[0,1]). Эта функция позволяет поместить график в произвольную область рисунка. Если параметр rel=true
, то используется позиция относительно текущего subplot (или inplot с rel=false
). Функция сбрасывает матрицу трансформации (повороты и сжатие графика) и должна вызываться первой для создания "подграфика".
num ind [d=0]
Помещает последующий вывод в ind-ую строку столбца из num строк. Положение столбца выбирается относительно последнего вызова subplot (или inplot с rel=false
). Параметр d задает дополнительный зазор между строк.
nx ny ind [d=0]
Помещает последующий вывод в ind-ую ячейку таблицы nx*ny. Положение ячейки выбирается относительно последнего вызова subplot (или inplot с rel=false
). Параметр d задает дополнительный зазор между строк.
num ind tet phi
Помещает последующий вывод в ind-ую ячейку "бруска" из num ячеек. При этом сам брусок повернут на углы tet, phi. Положение выбирается относительно последнего вызова subplot (или inplot с rel=false
).
num ind sx sy [xd yd]
Помещает последующий вывод в ind-ую ячейку "бруска" из num ячеек. При этом сама ячейка скошена на sx, sy. Направление бруска задается переменными xd и yd. Положение выбирается относительно последнего вызова subplot (или inplot с rel=false
).
size=-2
]Выводит заголовок title для текущего "подграфика" шрифтом stl с размером size. Если строка stl содержит ‘#’, то рисуется обрамляющий прямоугольник. Функция сбрасывает матрицу трансформации (повороты и сжатие графика) и должна вызываться сразу после создания "подграфика".
tetx tetz [tety=0]
Вращает систему координат относительно осей {x, z, y} последовательно на углы TetX, TetZ, TetY.
tet x y z
Вращает систему координат относительно вектора {x, y, z} на угол Tet.
sx sy
Сдвигает (скашивает) систему координат на значения sx, sy.
ax ay [az=1]
Устанавливает соотношение размеров осей в отношении Ax:Ay:Az. Для лучшего вида следует вызывать после функции rotate. Если Ax=NAN
, то функция выберет оптимальное соотношение размеров, чтобы шаг по осям x-y был одинаков. При этом, Ay задает фактор пропорциональности шага (обычно 1), или указывает на его автоматический выбор при Ay=NAN
.
Также есть 3 функции, которые управляют перспективой Perspective()
, масштабированием Zoom()
и вращением View()
всего рисунка. Т.е. они действуют как ещё одна матрица трансформации. Они были введены для вращения/приближения графика с помощью мыши. Не рекомендуется вызывать их при рисовании графика.
val
Добавляет (включает) перспективу для графика. Параметр a = Depth/(Depth+dz) \in [0,1). По умолчанию (a=0
) перспектива отключена.
tetx tetz [tety=0]
Вращает систему координат относительно осей {x, z, y} последовательно на углы TetX, TetZ, TetY. Вращение происходит независимо от rotate. Внимание! эти настройки не могут быть переписаны функцией DefaultPlotParam()
. Используйте Zoom(0,0,1,1)
для возвращения к виду по умолчанию.
x1 y1 x2 y2
Масштабирует весь рисунок. После вызова функции текущий график будет очищен и в дальнейшем рисунок будет содержать только область [x1,x2]*[y1,y2] от исходного рисунка. Координаты x1, x2, y1, y2 меняются в диапазоне от 0 до 1. Внимание! эти настройки не могут быть переписаны никакими другими функциями, включая DefaultPlotParam()
. Используйте Zoom(0,0,1,1)
для возвращения к виду по умолчанию.
Next: Background, Previous: Subplots and rotation, Up: MathGL core [Contents][Index]
Функции в этой группе сохраняют или дают доступ к полученному рисунку. Поэтом обычно они должны вызываться в конце рисования.
w h
Изменяет размер картинки в пикселях. Функция должна вызываться перед любыми функциями построения потому что полностью очищает содержимое рисунка при clear=true
. Функция только очищает растровый рисунок и масштабирует примитивы при clear=false
.
factor
Задает множитель для высоты и ширины во всех последующих вызовах setsize.
val
=2]Задает качество графика в зависимости от значения val: MGL_DRAW_WIRE=0
– нет рисования граней (наиболее быстрый), MGL_DRAW_FAST=1
– нет интерполяции цвета (быстрый), MGL_DRAW_NORM=2
– высокое качество (нормальный), MGL_DRAW_HIGH=3
– высокое качество с рисованием 3d примитивов (стрелок и маркеров). Если установлен бит MGL_DRAW_LMEM=0x4
, то происходит прямое рисование в растровое изображение (меньше затраты памяти). Если установлен бит MGL_DRAW_DOTS=0x8
, то рисуются точки вместо примитивов (очень быстро).
• Export to file: | ||
• Frames/Animation: | ||
• Bitmap in memory: | ||
• Parallelization: |
Next: Frames/Animation, Up: Export picture [Contents][Index]
Эти функции экспортируют текущую картинку (кадр) в файл. Имя файла fname должно иметь соответствующее расширение. Параметр descr дает краткое описание картинки. Пока прозрачность поддерживается только для форматов PNG, SVG, OBJ и PRC.
Экспортирует текущий кадр в файл fname с типом, определяемым по расширению. Параметр descr добавляет описание (может быть пустым). Если fname пустой, то используется имя ‘frame####.jpg’, где ‘####’ – текущий номер кадра и имя ‘frame’ определяется переменной plotid.
Next: Bitmap in memory, Previous: Export to file, Up: Export picture [Contents][Index]
В MGL нет специальных команд для создания анимации. Однако можно воспользоваться возможностями утилит mglconv
и mglview
. Например, используя комментарии спеиального вида ‘##a ’ или ‘##c ’.
Next: Parallelization, Previous: Frames/Animation, Up: Export picture [Contents][Index]
Previous: Bitmap in memory, Up: Export picture [Contents][Index]
Next: Primitives, Previous: Export picture, Up: MathGL core [Contents][Index]
These functions change background image.
Очищает рисунок и заполняет фон заданным цветом.
Завершает рисование графика и помещает результат в качестве фона. После этого, очищает список примитивов (как clf). Функция полезна для сохранения части графика (например, поверхностей или векторных полей) в растровом виде, а другой части (кривых, осей и пр.) в векторном.
alpha=1
]Загружает PNG или JPEG файл fname в качестве фона для графика. Параметр alpha задает прозрачность фона вручную.
Next: Text printing, Previous: Export picture, Up: MathGL core [Contents][Index]
Эти функции рисуют рисуют простые объекты типа линий, точек, сфер, капель, конусов, и т.д.
x y
['col'='r.']x y z
['col'='r.']Рисует маркер (точку по умолчанию) с координатами p={x, y, z} и цветом col.
x y ex ey
['stl'='']x y z ex ey ez
['stl'='']Рисует 3d error box в точке p={x, y, z} размером e={ex, ey, ez} и стилем stl. Используйте NAN в компонентах e для уменьшения рисуемых элементов.
x1 y1 x2 y2
['stl'='']x1 y1 z1 x2 y2 z2
['stl'='']Рисует геодезическую линию (декартовых координатах – прямую) из точки p1 в p2 использую стиль линии stl. Параметр num определяет гладкость линии (число точек на линии). Если num=2
, то рисуется прямая даже в криволинейных координатах (см. Curved coordinates). Наоборот, для больших значений (например, =100
) рисуется геодезическая линия (окружность в полярных координатах, парабола в параболических и т.д.). Линия рисуется даже если часть ее лежит вне диапазона осей координат.
x1 y1 dx1 dy1 x2 y2 dx2 dy2
['stl'='']x1 y1 z1 dx1 dy1 dz1 x2 y2 z2 dx2 dy2 dz2
['stl'='']Рисует кривую Безье из точки p1 в p2 используя стиль линии stl. Касательные в точках пропорциональны d1, d2. Параметр num определяет гладкость линии (число точек на линии). Если num=2
, то рисуется прямая даже в криволинейных координатах (см. Curved coordinates). Наоборот, для больших значений (например, =100
) рисуется геодезическая линия (окружность в полярных координатах, парабола в параболических и т.д.). Кривая рисуется даже если часть ее лежит вне диапазона осей координат.
x1 y1 x2 y2 x3 y3 x4 y4
['stl'='']x1 y1 z1 x2 y2 z2 x3 y3 z3 x4 y4 z4
['stl'='']Рисует заполненный четырехугольник (грань) с углами в точках p1, p2, p3, p4 и цветом(-ами) stl. При этом цвет может быть один для всей грани, или различным если указаны все 4 цвета. Грань будет нарисована даже если часть ее лежит вне диапазона осей координат.
x1 y1 x2 y2
['stl'='']x1 y1 z1 x2 y2 z2
['stl'='']Рисует закрашенный прямоугольник (грань) с вершинами {x1, y1, z1} и {x2, y2, z2} цветом stl. При этом цвет может быть один для всей грани, или различным для разных вершин если указаны все 4 цвета. Грань будет нарисована даже если часть ее лежит вне диапазона осей координат.
x0 y0 z0 wy wz
['stl'='' d1=0 d2=0
]x0 y0 z0 wx wz
['stl'='' d1=0 d2=0
]x0 y0 z0 wx wy
['stl'='' d1=0 d2=0
]Рисует закрашенный прямоугольник (грань) перпендикулярно оси [x,y,z] в точке {x0, y0, z0} цветом stl и шириной wx, wy, wz вдоль соответствующего направления. При этом цвет может быть один для всей грани, или различным для разных вершин если указаны все 4 цвета. Параметры d1!=0, d2!=0 задают дополнительный сдвиг последней точки (т.е. рисуют четырехугольник). Грань будет нарисована даже если часть ее лежит вне диапазона осей координат.
x0 y0 r
['col'='r']x0 y0 z0 r
['col'='r']Рисует сферу радиуса r с центром в точке p={x0, y0, z0} цветом stl.
x0 y0 dx dy r
['col'='r' sh=1 asp=1
]x0 y0 z0 dx dy dz r
['col'='r' sh=1 asp=1
]Рисует каплю радиуса r в точке p вытянутую вдоль направления d цветом col. Параметр shift определяет степень вытянутости: ‘0’ – сфера, ‘1’ – классическая капля. Параметр ap определяет относительную ширину капли (аналог "эллиптичности" для сферы).
x1 y1 z1 x2 y2 z2 r1
[r2=-1
'stl'='' edge=off
]Рисует трубу (или усеченный конус если edge=false
) между точками p1, p2 с радиусами на концах r1, r2. Если r2<0, то полагается r2=r1. Цвет конуса задается строкой stl. Параметр stl может содержать:
x0 y0 r
['col'='r']x0 y0 z0 r
['col'='r']Рисует круг радиуса r с центром в точке p={x0, y0, z0} цветом stl. Если col содержит: ‘#’ то рисуется только граница, ‘@’ то рисуется граница (вторым цветом из col или черными).
x1 y1 x2 y2 r
['col'='r']x1 y1 z1 x2 y2 z2 r
['col'='r']Рисует круг радиуса r с фокусами в точках p1, p2 цветом stl. Если col содержит: ‘#’ то рисуется только граница, ‘@’ то рисуется граница (вторым цветом из col или черными).
x1 y1 x2 y2 r
['col'='r']x1 y1 z1 x2 y2 z2 r
['col'='r']Рисует ромб ширины r с вершинами в точках p1, p2 цветом stl. Если col содержит: ‘#’ то рисуется только граница, ‘@’ то рисуется граница (вторым цветом из col или черными). Если col содержит 3 цвета, то используется градиентная заливка.
x0 y0 x1 y1 a
['col'='r']x0 y0 z0 x1 y1 a
['col'='r']x0 y0 z0 xa ya za x1 y1 z1 a
['col'='r']Рисует дугу вокруг оси pa (по умолчанию вокруг оси z pa={0,0,1}) с центром в p0, начиная с точки p1. Параметр a задает угол дуги в градусах. Строка col задает цвет дуги и тип стрелок на краях.
x0 y0 x1 y1 num
['col'='r']x0 y0 z0 x1 y1 z1 num
['col'='r']Рисует правильный num-угольник с центром в p0 с первой вершиной в p1 цветом col. Если col содержит: ‘#’ то рисуется только граница, ‘@’ то рисуется граница (вторым цветом из col или черными).
Draw bitmap (logo) along whole axis range, which can be changed by Command options. Bitmap can be loaded from file or specified as RGBA values for pixels. Parameter smooth set to draw bitmap without or with color interpolation.
Next: Axis and Colorbar, Previous: Primitives, Up: MathGL core [Contents][Index]
Функции для вывода текста позволяют вывести строку текста в произвольном месте рисунка, в произвольном направлении и вдоль произвольной кривой. MathGL позволяет использовать произвольное начертание шрифта и многие ТеХ-ие команды (детальнее см. Font styles). Все функции вывода текста имеют варианты для 8-bit строк (char *
) и для Unicode строк (wchar_t *
). В первом случае используется конверсия из текущей локали, т.е. иногда вам требуется явно указать локаль с помощью функции setlocale()
. Аргумент size определяет размер текста: размер шрифта если положителен или относительный размер (=-size*SetFontSize()
) если отрицателен. Начертание шрифта (STIX, arial, courier, times и др.) можно изменить с помощью функции LoadFont(). See Font settings.
Параметры шрифта задаются строкой, которая может содержать символы цвета ‘wkrgbcymhRGBCYMHW’ (см. Color styles). Также после символа ‘:’ можно указать символы стиля (‘rbiwou’) и/или выравнивания (‘LRCTV’). Стили шрифта: ‘r’ – прямой, ‘i’ – курсив, ‘b’ – жирный, ‘w’ – контурный, ‘o’ – надчеркнутый, ‘u’ – подчеркнутый. По умолчанию используется прямой шрифт. Типы выравнивания: ‘L’ – по левому краю (по умолчанию), ‘C’ – по центру, ‘R’ – по правому краю, ‘T’ – под текстом, ‘V’ – по центру вертикально. Например, строка ‘b:iC’ соответствует курсиву синего цвета с выравниванием по центру. Начиная с MathGL версии 2.3, вы можете задать цветовой градиент для выводимой строки (см. Color scheme).
Если строка содержит символы ‘aA’, то текст выводится в абсолютных координатах (полагаются в диапазоне [0,1]). При этом используются координаты относительно рисунка (если указано ‘A’) или относительно последнего subplot/inplot (если указано ‘a’). Если строка содержит символ ‘@’, то вокруг текста рисуется прямоугольник.
См. Text features, для примеров кода и графика.
x y
'text' ['fnt'='' size=-1
]x y z
'text' ['fnt'='' size=-1
]Выводит строку text от точки p шрифтом определяемым строкой fnt. Размер шрифта задается параметром size (по умолчанию -1
).
x y dx dy
'text' ['fnt'=':L' size=-1
]x y z dx dy dz
'text' ['fnt'=':L' size=-1
]Выводит строку text от точки p вдоль направления d. Параметр fnt задает стиль текста и указывает выводить текст под линией (‘T’) или над ней (‘t’).
x y
'fname' [n=0
'fnt'='' size=-1.4
]x y z
'fname' [n=0
'fnt'='' size=-1.4
]Выводит n-ую строку файла fname от точки {x,y,z} шрифтом fnt и размером size. По умолчанию используются параметры заданные командой font.
size=-1 zval=nan
]size=-1
]Выводит строку text вдоль кривой {x[i], y[i], z[i]} шрифтом fnt. Строка fnt может содержать символы: ‘t’ для вывода текста под кривой (по умолчанию), или ‘T’ для вывода текста под кривой. Размеры по 1-ой размерности должны быть одинаковы для всех массивов x.nx=y.nx=z.nx
. Если массив x не указан, то используется "автоматический" массив со значениями в диапазоне осей координат (см. Ranges (bounding box)). Если массив z не указан, то используется минимальное значение оси z. Строка opt содержит опции команды (см. Command options).
Next: Legend, Previous: Text printing, Up: MathGL core [Contents][Index]
Эти функции рисуют объекты для "измерения" типа осей координат, цветовой таблицы (colorbar), сетку по осям, обрамляющий параллелепипед и подписи по осям координат. См. также см. Axis settings.
Рисует оси координат и метки на них (см. Axis settings) в направлениях ‘xyz’, указанных строкой dir. Строка dir может содержать:
Стиль меток и оси(ей) задается строкой stl. Опция value
задает угол вращения меток оси. См. Axis and ticks, для примеров кода и графика.
Рисует полосу соответствия цвета и числовых значений (colorbar) для цветовой схемы sch (используется текущая для sch=""
) с краю от графика. Строка sch также может содержать:
См. Colorbars, для примеров кода и графика.
Аналогично предыдущему, но для цветовой схемы без сглаживания с заданными значениями v. См. ContD sample, для примеров кода и графика.
x y [w=1 h=1]
Аналогично первому, но в произвольном месте графика {x, y} (полагаются в диапазоне [0,1]). Параметры w, h задают относительную ширину и высоту colorbar.
x y [w=1 h=1]
Аналогично предыдущему, но для цветовой схемы sch без сглаживания с заданными значениями v. См. ContD sample, для примеров кода и графика.
Рисует линии сетки в направлениях перпендикулярным dir. Если dir содержит ‘!’, то линии рисуются также и для координат под-меток. Шаг сетки такой же как у меток осей координат. Стиль линий задается параметром pen (по умолчанию – сплошная темно синяя линия ‘B-’).
ticks=on
]Рисует ограничивающий параллелепипед цветом col. Если col содержит ‘@’, то рисуются закрашенные задние грани. При этом первый цвет используется для граней (по умолчанию светло жёлтый), а последний для рёбер и меток.
pos=1
]pos=1
]pos=1
]pos=1
]Выводит подпись text для оси dir=‘x’,‘y’,‘z’,‘t’ (где ‘t’ – “тернарная” ось t=1-x-y). Параметр pos задает положение подписи: при pos=0 – по центру оси, при pos>0 – около максимальных значений, при pos<0 – около минимальных значений. Опция value
задает дополнительный сдвиг текста. See Text printing.
Next: 1D plotting, Previous: Axis and Colorbar, Up: MathGL core [Contents][Index]
Эти функции обеспечивают рисование легенды графика (полезно для 1D plotting). Запись в легенде состоит из двух строк: одна для стиля линии и маркеров, другая с текстом описания (с включенным разбором TeX-их команд). Можно использовать непосредственно массивы строк, или накопление во внутренние массивы с помощью функции AddLegend() с последующим отображением. Положение легенды можно задать автоматически или вручную. Параметры fnt и size задают стиль и размер шрифта (см. Font settings). Параметр llen задает относительную ширину примера линии. Ели стиль линии пустой, то соответствующий текст печатается без отступа. Если строка fnt содержит символ ‘A’, то координаты легенды считаются относительно картинки (а не текущего subplot). Если строка fnt содержит символ ‘^’, то легенда располагается снаружи от указанных координат. Если строка fnt содержит символ ‘#’, то рисуется прямоугольник вокруг легенды. См. Legend sample, для примеров кода и графика.
pos=3
'fnt'='#']Рисует легенду из накопленных записей шрифтом fnt размером size. Параметр pos задает положение легенды: ‘0’ – в нижнем левом углу, ‘1’ – нижнем правом углу, ‘2’ – верхнем левом углу, ‘3’ – верхнем правом углу (по умолчанию). Строка fnt может содержать вет для прямоугольника (1-ый цвет), для его границы (2-ой цвет) и для текста (последний). Если указано менее 3 цветов, то цвет рёбер будет чёрным (2 и менее цвета), а цвет прямоугольника белым (1 и менее цвета). Прямоугольник рисуется если строка fnt содержит ‘#’. Если строка fnt содержит ‘-’, то записи располагаются горизонтально. Опция value
задает зазор между примером линии и текстом (по умолчанию 0.1).
x y
['fnt'='#']Рисует легенду из накопленных записей шрифтом fnt размером size. Положение легенды задается параметрами x, y, которые полагаются нормированными в диапазоне [0,1]. Опция value
задает зазор между примером линии и текстом (по умолчанию 0.1).
Добавляет описание text кривой со стилем style (см. Line styles) во внутренний массив записей легенды.
Очищает внутренний массив записей легенды.
val
Задает число маркеров в легенде. По умолчанию используется 1 маркер.
Next: 2D plotting, Previous: Legend, Up: MathGL core [Contents][Index]
Эти функции строят графики для одномерных (1D) массивов. Одномерными считаются массивы, зависящие только от одного параметра (индекса) подобно кривой в параметрической форме {x(i),y(i),z(i)}, i=1...n. По умолчанию (если отсутствуют) значения x[i] равно распределены в диапазоне оси х, и z[i] равно минимальному значению оси z. Графики рисуются для каждой строки массива данных если он двумерный. Размер по 1-ой координате должен быть одинаков для всех массивов x.nx=y.nx=z.nx
.
Строка pen задает цвет и стиль линии и маркеров (см. Line styles). По умолчанию (pen=""
) рисуется сплошная линия с текущим цветом из палитры (см. Palette and colors). Символ ‘!’ в строке задает использование нового цвета из палитры для каждой точки данных (не для всей кривой, как по умолчанию). Строка opt задает опции графика (см. Command options). См. 1D samples, для примеров кода и графика.
Функции рисуют ломанную линию по точкам {x[i], y[i], z[i]}. См. также area, step, stem, tube, mark, error, belt, tens, tape. См. Plot sample, для примеров кода и графика.
Функции рисуют radar chart, представляющий собой ломанную с вершинами на радиальных линиях (типа ломанной в полярных координатах). Параметр value
в опциях opt задает дополнительный сдвиг данных (т.е. использование a+value
вместо a). Если pen содержит ‘#’, то рисуется "сетка" (радиальные линии). См. также plot. См. Radar sample, для примеров кода и графика.
Функции рисуют ступеньки для точек массива. См. также plot, stem, tile, boxs. См. Step sample, для примеров кода и графика.
Функции рисуют ломанную линию по точкам с цветом, определяемым массивом c (типа графика натяжений). Строка pen задает цветовую схему (см. Color scheme) и стиль линий и/или маркеров (см. Line styles). См. также plot, mesh, fall. См. Tens sample, для примеров кода и графика.
Функции рисуют ленты, которые вращаются вокруг кривой {x[i], y[i], z[i]} как её нормали. Начальная лента(ы) выбираются в плоскости x-y (для ‘x’ в pen) и/или y-z (для ‘x’ в pen). Ширина лент пропорциональна barwidth, а также может быть изменена опцией value
. См. также plot, flow, barwidth. См. Tape sample, для примеров кода и графика.
Функции рисуют ломанную линию между точками и закрашивает её вниз до плоскости осей координат. Градиентная заливка используется если число цветов равно удвоенному число кривых. См. также plot, bars, stem, region. См. Area sample, для примеров кода и графика.
Функции закрашивают область между 2 кривыми. Градиентная заливка используется если число цветов равно удвоенному число кривых. Если в 2d версии pen содержит ‘i’, то закрашивается только область y1<y<y2, в противном случае будет закрашена и область y2<y<y1. См. также area, bars, stem. См. Region sample, для примеров кода и графика.
Функции рисуют вертикальные линии из точек до плоскости осей координат. См. также area, bars, plot, mark. См. Stem sample, для примеров кода и графика.
Функции рисуют вертикальные полосы (прямоугольники) из точек до плоскости осей координат. Если строка pen содержит символ ‘a’, то линии рисуются одна поверх другой. Если строка содержит символ ‘f’, то рисуется график типа waterfall для определения кумулятивного эффекта последовательности положительных и отрицательных значений. Можно использовать разные цвета для положительных и отрицательных значений если число указанных цветов равно удвоенному числу кривых для построения. Если pen содержит ‘<’, ‘^’ или ‘>’, то полоски будут выровнены влево, вправо или центрированы относительно их координат. См. также barh, cones, area, stem, chart, barwidth. См. Bars sample, для примеров кода и графика.
Функции рисуют горизонтальные полосы (прямоугольники) из точек до плоскости осей координат. Если строка pen содержит символ ‘a’, то линии рисуются одна поверх другой. Если строка содержит символ ‘f’, то рисуется график типа waterfall для определения кумулятивного эффекта последовательности положительных и отрицательных значений. Можно использовать разные цвета для положительных и отрицательных значений если число указанных цветов равно удвоенному числу кривых для построения. Если pen содержит ‘<’, ‘^’ или ‘>’, то полоски будут выровнены влево, вправо или центрированы относительно их координат. См. также bars, barwidth. См. Barh sample, для примеров кода и графика.
Функции рисуют конусы из точек до плоскости осей координат. Если строка pen содержит символ ‘a’, то линии рисуются одна поверх другой. Можно использовать разные цвета для положительных и отрицательных значений если число указанных цветов равно удвоенному числу кривых для построения. Параметр pen может содержать:
См. также bars, cone, barwidth. См. Cones sample, для примеров кода и графика.
Рисует цветные полосы (пояса) для массива данных a. Число полос равно числу строк a (равно a.ny). Цвет полос поочерёдно меняется из цветов указанных в col или в палитре (см. Palette and colors). Пробел в цветах соответствует прозрачному "цвету", т.е. если col содержит пробел(ы), то соответствующая полоса не рисуется. Ширина полосы пропорциональна значению элемента в a. График строится только для массивов не содержащих отрицательных значений. Если строка col содержит ‘#’, то рисуется также чёрная граница полос. График выглядит лучше в (после вращения системы координат) и/или в полярной системе координат (становится Pie chart). См. Chart sample, для примеров кода и графика.
Функции рисуют boxplot (называемый также как box-and-whisker diagram или как "ящик с усами") в точках x[i] на плоскости z = zVal (по умолчанию z равно минимальному значению оси z). Это график, компактно изображающий распределение вероятностей a[i,j] (минимум, нижний квартиль (Q1), медиана (Q2), верхний квартиль (Q3) и максимум) вдоль второго (j-го) направления. Если pen содержит ‘<’, ‘^’ или ‘>’, то полоски будут выровнены влево, вправо или центрированы относительно их координат. См. также plot, error, bars, barwidth. См. BoxPlot sample, для примеров кода и графика.
Функции рисуют candlestick chart в точках x[i]. Этот график показывает прямоугольником ("свечой") диапазон изменения величины. Прозрачная (белая) свеча соответствует росту величины v1[i]<v2[i], чёрная – уменьшению. "Тени" показывают минимальное y1 и максимальное y2 значения. Если v2 отсутствует, то он определяется как v2[i]=v1[i+1]. Можно использовать разные цвета для растущих и падающих дней если число указанных цветов равно удвоенному числу кривых для построения. Если pen содержит ‘#’, то прозрачная свеча будет использована и при 2-цветной схеме. См. также plot, bars, ohlc, barwidth. См. Candle sample, для примеров кода и графика.
Функции рисуют Open-High-Low-Close диаграмму. Этот график содержит вертикальные линии между максимальным h и минимальным l значениями, и горизонтальные линии перед/после вертикальной линии для начального o и конечного c значений процесса (обычно цены). Можно использовать разные цвета для растущих и падающих дней если число указанных цветов равно удвоенному числу кривых для построения. См. также candle, plot, barwidth. См. OHLC sample, для примеров кода и графика.
Функции рисуют размер ошибки {ex[i], ey[i]} в точках {x[i], y[i]} на плоскости z = zVal (по умолчанию z равно минимальному значению оси z). Такой график полезен для отображения ошибки эксперимента, вычислений и пр. Если pen содержит ‘@’, то будут использованы большие полупрозрачные маркеры. См. также plot, mark. См. Error sample, для примеров кода и графика.
Функции рисуют маркеры размером r[i]*marksize (см. Default sizes) в точках {x[i], y[i], z[i]}. Для рисования маркеров одинакового размера можно использовать функцию plot с невидимой линией (со стилем содержащим ‘ ’). Для маркеров с размером как у координат можно использовать error со стилем ‘@’. См. также plot, textmark, error, stem. См. Mark sample, для примеров кода и графика.
Функции рисуют текст txt как маркер с размером пропорциональным r[i]*marksize в точках {x[i], y[i], z[i]}. См. также plot, mark, stem. См. TextMark sample, для примеров кода и графика.
Функции выводят текстовую строку txt в точках {x[i], y[i], z[i]}. Если строка txt содержит ‘%x’, ‘%y’, ‘%z’ или ‘%n’, то они будут заменены на значения соответствующих координат или на номер точки. Строка fnt может содержать:
См. также plot, mark, textmark, table. См. Label sample, для примеров кода и графика.
Рисует таблицу значений массива val с заголовками txt (разделенными символом новой строки ‘\n’) в точке {x, y} (по умолчанию {0,0}) относительно текущего subplot. Строка fnt может содержать:
Опция value
задает ширину таблицы (по умолчанию 1). См. также label. См. Table sample, для примеров кода и графика.
rval
['stl'='']rval
['stl'='']rval
['stl'='']Функции рисуют трубу радиуса r[i] вдоль кривой между точками {x[i], y[i], z[i]}. См. также plot. См. Tube sample, для примеров кода и графика.
Функции рисуют поверхность вращения кривой {r, z} относительно оси. Если строка pen содержит ‘x’ или ‘z’, то ось вращения будет выбрана в указанном направлении (по умолчанию вдоль оси y). Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также plot, axial. См. Torus sample, для примеров кода и графика.
x0
ydat ['stl'='']x0
'y(x)' ['stl'='']Функции рисуют диаграмму Ламерея для точечного отображения x_new = y(x_old) начиная с точки x0. Строка stl может содержать стиль линии, символ ‘v’ для стрелок, символ ‘~’ для исключения первого сегмента. Опция value
задает число сегментов для рисования (по умолчанию 20). См. также plot, fplot, bifurcation, pmap. См. Lamerey sample, для примеров кода и графика.
dx
ydat ['stl'='']dx
'y(x)' ['stl'='']Функции рисуют бифуркационную диаграмму (диаграмму удвоения периода) для точечного отображения x_new = y(x_old). Параметр dx задает точность по оси x. Строка stl задает цвет. Опция value
задает число учитываемых стационарных точек (по умолчанию 1024). См. также plot, fplot, lamerey. См. Bifurcation sample, для примеров кода и графика.
Функции рисуют отображение Пуанкаре для кривой {x, y, z} при условии s=0. Проще говоря, рисуются точки пересечения кривой и поверхности. Строка stl задает стиль маркеров. См. также plot, mark, lamerey. См. Pmap sample, для примеров кода и графика.
Next: 3D plotting, Previous: 1D plotting, Up: MathGL core [Contents][Index]
Эти функции строят графики для двумерных (2D) массивов. Двумерными считаются массивы, зависящие только от двух параметров (индексов) подобно матрице f(x_i,y_j), i=1...n, j=1...m. По умолчанию (если отсутствуют) значения x, y равно распределены в диапазоне осей координат. Младшие размерности массивов x, y, z должны быть одинаковы x.nx=z.nx && y.nx=z.ny
или x.nx=y.nx=z.nx && x.ny=y.ny=z.ny
. Массивы x и y могут быть векторами (не матрицами как z). График строится для каждого z среза данных. Строка sch задает цветовую схему (см. Color scheme). Строка opt задает опции графика (см. Command options). См. 2D samples, для примеров кода и графика.
Рисует параметрически заданную поверхность {x[i,j], y[i,j], z[i,j]}. Если sch содержит ‘#’, то рисуется сетка на поверхности. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также mesh, dens, belt, tile, boxs, surfc, surfa. См. Surf sample, для примеров кода и графика.
Рисует сетчатую поверхность, заданную параметрически {x[i,j], y[i,j], z[i,j]}. См. также surf, fall, meshnum, cont, tens. См. Mesh sample, для примеров кода и графика.
Рисует водопад для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. График удобен для построения нескольких кривых, сдвинутых вглубь друг относительно друга. Если sch содержит ‘x’, то линии рисуются вдоль оси x, иначе (по умолчанию) вдоль оси y. См. также belt, mesh, tens, meshnum. См. Fall sample, для примеров кода и графика.
Рисует ленточки для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. График может использоваться как 3d обобщение графика plot. Если sch содержит ‘x’, то ленточки рисуются вдоль оси x, иначе (по умолчанию) вдоль оси y. См. также fall, surf, plot, meshnum. См. Belt sample, для примеров кода и графика.
Рисует вертикальные ящики для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. См. также surf, dens, tile, step. См. Boxs sample, для примеров кода и графика.
Рисует плитки для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. График может использоваться как 3d обобщение step. См. также surf, boxs, step, tiles. См. Tile sample, для примеров кода и графика.
Рисует график плотности для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z равном минимальному значению оси z. Если sch содержит ‘#’, то рисуется сетка. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также surf, cont, contf, boxs, tile, dens[xyz]
. См. Dens sample, для примеров кода и графика.
Рисует линии уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z=v[k] или при z равном минимальному значению оси z если sch содержит ‘_’. Линии уровня рисуются для z[i,j]=v[k]. Если sch содержит ‘t’ или ‘T’, то значения v[k] будут выведены вдоль контуров над (или под) кривой. См. также dens, contf, contd, axial, cont[xyz]
. См. Cont sample, для примеров кода и графика.
Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7).
Рисует закрашенные линии (контуры) уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z=v[k] или при z равном минимальному значению оси z если sch содержит ‘_’. Линии уровня рисуются для z[i,j]=v[k]. См. также dens, cont, contd, contf[xyz]
. См. ContF sample, для примеров кода и графика.
Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7).
Рисует закрашенные линии (контуры) уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z=v[k] или при z равном минимальному значению оси z если sch содержит ‘_’. Линии уровня рисуются для z[i,j]=v[k]. Строка sch задает цвета контуров: цвет k-го контура определяется как k-ый цвет строки. См. также dens, cont, contf. См. ContD sample, для примеров кода и графика.
Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7).
Рисует вертикальные цилиндры от линий уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z=v[k] или при z равном минимальному значению оси z если sch содержит ‘_’. Линии уровня рисуются для z[i,j]=v[k]. См. также cont, contf. См. ContV sample, для примеров кода и графика.
Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7).
Рисует поверхность вращения линии уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. Линии уровня рисуются для z[i,j]=v[k]. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. Если строка содержит символы ‘x’ или ‘z’, то ось вращения устанавливается в указанное направление (по умолчанию вдоль ‘y’). См. также cont, contf, torus, surf3. См. Axial sample, для примеров кода и графика.
Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 3).
Рисует плоскую сету для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z равном минимальному значению оси z. См. также dens, cont, contf, grid3, meshnum.
Next: Dual plotting, Previous: 2D plotting, Up: MathGL core [Contents][Index]
Эти функции строят графики для трехмерных (3D) массивов. Трёхмерными считаются массивы, зависящие от трёх параметров (индексов) подобно матрице f(x_i,y_j,z_k), i=1...n, j=1...m, k=1...l. По умолчанию (если отсутствуют) значения x, y, z равно распределены в диапазоне осей координат. Младшие размерности массивов x, y, z должны быть одинаковы x.nx=a.nx && y.nx=a.ny && z.nz=a.nz
или x.nx=y.nx=z.nx=a.nx && x.ny=y.ny=z.ny=a.ny && x.nz=y.nz=z.nz=a.nz
. Массивы x, y и z могут быть векторами (не матрицами как a). Строка sch задает цветовую схему (см. Color scheme). Строка opt задает опции графика (см. Command options). См. 3D samples, для примеров кода и графика.
val
['sch'='']val
['sch'='']Рисует поверхность уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) при a(x,y,z)=val. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. Замечу, что возможно некорректная отрисовка граней вследствие неопределённости построения сечения если поверхность пересекает ячейку данных 2 и более раз. См. также cloud, dens3, surf3c, surf3a, axial. См. Surf3 sample, для примеров кода и графика.
Аналогично предыдущему для num поверхностей уровня равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 3).
Рисует облачный график для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). График состоит из кубиков с цветом и прозрачностью пропорциональной значениям a. Результат похож на облако – малые значения прозрачны, а большие нет. Число кубиков зависит от meshnum. Если sch содержит ‘.’, то будет построен график более низкого качества, но с заметно меньшим использованием памяти. Если sch содержит ‘i’, то прозрачность будет инвертирована, т.е. области с более высокими значениями будут более прозрачны, а с более низким – менее прозрачны. См. также surf3, meshnum. См. Cloud sample, для примеров кода и графика.
sval=-1
]sval=-1
]Рисует график плотности для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). График рисуется на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). Если sch содержит ‘#’, то на срезе рисуется сетка. См. также cont3, contf3, dens, grid3. См. Dens3 sample, для примеров кода и графика.
sval=-1
]sval=-1
]Рисует линии уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Линии рисуются для значений из массива v на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). Если sch содержит ‘#’, то на срезе рисуется сетка. Если sch содержит ‘t’ или ‘T’, то значения v[k] будут выведены вдоль контуров над (или под) кривой. См. также dens3, contf3, cont, grid3. См. Cont3 sample, для примеров кода и графика.
sval=-1
]sval=-1
]Аналогично предыдущему для num линий уровня равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 7).
sval=-1
]sval=-1
]Рисует закрашенные линии (контуры) уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Линии рисуются для значений из массива v на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). Если sch содержит ‘#’, то на срезе рисуется сетка. См. также dens3, cont3, contf, grid3. См. ContF3 sample, для примеров кода и графика.
sval=-1
]sval=-1
]Аналогично предыдущему для num закрашенных линий (контуров) уровня равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 7).
sval=-1
]sval=-1
]Рисует сетку для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). График рисуется на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). См. также cont3, contf3, dens3, grid2, meshnum.
rval
['sch'='' flag=0 num=3
]Рисует поверхность уровня для 3d массива a при постоянном значении a=val. Это специальный тип графика для a заданного в сопровождающей системе координат вдоль кривой tr с ортами g1, g2 и с поперечным размером r. Переменная flag – битовый флаг: ‘0x1’ - рисовать в сопровождающих (не лабораторных) координатах; ‘0x2’ - рисовать проекцию на плоскость \rho-z; ‘0x4’ - рисовать нормированное в каждом сечении поле. Размеры массивов по 1-му индексу tr, g1, g2 должны быть nx>2. Размеры массивов по 2-му индексу tr, g1, g2 и размер по 3-му индексу массива a должны быть одинаковы. См. также surf3.
Next: Vector fields, Previous: 3D plotting, Up: MathGL core [Contents][Index]
Эти функции строят графики для двух связанных массивов. Есть несколько основных типов 3D графиков: поверхность и поверхность уровня с окраской по второму массиву (SurfC, Surf3C), поверхность и поверхность уровня с прозрачностью по второму массиву (SurfA, Surf3A), плитки переменного размера (TileS), диаграмма точечного отображения (Map), STFA диаграмма (STFA). По умолчанию (если отсутствуют) значения x, y (и z для Surf3C, Surf3A
) равно распределены в диапазоне осей координат. Младшие размерности массивов x, y, z, c должны быть одинаковы x.nx=a.nx && y.nx=a.ny && z.nz=a.nz
или x.nx=y.nx=z.nx=a.nx && x.ny=y.ny=z.ny=a.ny && x.nz=y.nz=z.nz=a.nz
. Массивы x, y (и z для Surf3C, Surf3A
) могут быть векторами (не матрицами как c). Строка sch задает цветовую схему (см. Color scheme). Строка opt задает опции графика (см. Command options).
Рисует параметрически заданную поверхность {x[i,j], y[i,j], z[i,j]} с цветом, заданным массивом c[i,j]. Если sch содержит ‘#’, то на поверхности рисуется сетка. Если sch содержит ‘.’, то рисуется поверхность из точек. Размерность массивов z и c должна быть одинакова. График строится для каждого z среза данных. См. также surf, surfa, surf3c. См. SurfC sample, для примеров кода и графика.
val
['sch'='']val
['sch'='']Рисует поверхность уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) при a(x,y,z)=val. Аналогично surf3, но цвет задается массивом c. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также surf3, surfc, surf3a. См. Surf3C sample, для примеров кода и графика.
Аналогично предыдущему для num поверхностей уровня равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 3).
Рисует параметрически заданную поверхность {x[i,j], y[i,j], z[i,j]} с прозрачностью, заданной массивом c[i,j]. Если sch содержит ‘#’, то на поверхности рисуется сетка. Если sch содержит ‘.’, то рисуется поверхность из точек. Размерность массивов z и c должна быть одинакова. График строится для каждого z среза данных. См. также surf, surfc, surf3a. См. SurfA sample, для примеров кода и графика.
val
['sch'='']val
['sch'='']Рисует поверхность уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) при a(x,y,z)=val. Аналогично surf3, но прозрачность задается массивом c. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также surf3, surfc, surf3a. См. Surf3A sample, для примеров кода и графика.
Аналогично предыдущему для num поверхностей уровня равномерно распределённых в диапазоне изменения цвета. При этом массив c может быть вектором со значениями прозрачности и num=c.nx. В противном случае величина num равна значению параметра value
в опциях opt (по умолчанию 3).
Рисует параметрически заданную поверхность {x[i,j], y[i,j], z[i,j]} с цветом и прозрачностью, заданными массивами c[i,j] и a[i,j] соответственно. Если sch содержит ‘#’, то на поверхности рисуется сетка. Если sch содержит ‘.’, то рисуется поверхность из точек. Размерность массивов z и c должна быть одинакова. График строится для каждого z среза данных. См. также surf, surfc, surfa, surf3ca. См. SurfCA sample, для примеров кода и графика.
val
['sch'='']val
['sch'='']Рисует поверхность уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) при a(x,y,z)=val. Аналогично surf3, но цвет и прозрачность задается массивами c и b соответственно. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также surf3, surfc, surf3a. См. Surf3A sample, для примеров кода и графика.
Аналогично предыдущему для num поверхностей уровня равномерно распределённых в диапазоне изменения цвета. Здесь величина num равна значению параметра value
в опциях opt (по умолчанию 3).
Рисует плитки для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. Аналогично Tile(), но размер плиток задается массивов r. Это создает эффект "прозрачности" при экспорте в файлы EPS. График строится для каждого z среза данных. См. также surfa, tile. См. TileS sample, для примеров кода и графика.
Рисует точечное отображение для матриц {ax, ay } параметрически зависящих от координат x, y. Исходное положение ячейки задает ее цвет. Высота пропорциональна якобиану J(ax,ay). График является аналогом диаграммы Арнольда ??? Если sch содержит ‘.’, то цветные точки рисуются в узлах матриц (полезно для "запутанного" отображения), иначе рисуются грани. См. Mapping visualization, для примеров кода и графика.
dn
['sch'='']dn
['sch'='']Рисует спектрограмму комплексного массива re+i*im для Фурье размером dn точек в плоскости z равно минимальному значению оси z. Параметр dn – любое чётное число. Например в 1D случае, результатом будет график плотности от массива res[i,j]=|\sum_d^dn exp(I*j*d)*(re[i*dn+d]+I*im[i*dn+d])|/dn размером {int(nx/dn), dn, ny}. Массивы re, im параметрически зависят от координат x, y. Все размеры массивов re и im должны быть одинаковы. Младшие размерности массивов x, y, re должны быть одинаковы. Массивы x и y могут быть векторами (не матрицами как re). См. STFA sample, для примеров кода и графика.
Next: Other plotting, Previous: Dual plotting, Up: MathGL core [Contents][Index]
Эти функции рисуют графики для 2D и 3D векторных полей. Есть несколько типов графиков: просто векторное поле (Vect), вектора вдоль траектории (Traj), векторное поле каплями (Dew), нити тока (Flow, FlowP), трубки тока (Pipe). По умолчанию (если отсутствуют) значения x, y и z равно распределены в диапазоне осей координат. Младшие размерности массивов x, y, z и ax должны быть одинаковы. Размеры массивов ax, ay и az должны быть одинаковы. Массивы x, y и z могут быть векторами (не матрицами как ax). Строка sch задает цветовую схему (см. Color scheme). Строка opt задает опции графика (см. Command options).
Рисует вектора {ax, ay, az} вдоль кривой {x, y, z}. Длина векторов пропорциональна \sqrt{ax^2+ay^2+az^2}. Строка pen задает цвет (см. Line styles). По умолчанию (pen=""
) используется текущий цвет из палитры (см. Palette and colors). Опция value
задает фактор длины векторов (если не нуль) или выбирать длину пропорционально расстоянию между точками кривой (если value=0
). Размер по 1-му индексу должен быть 2 или больше. График рисуется для каждой строки если один из массивов матрица. См. также vect. См. Traj sample, для примеров кода и графика.
Рисует векторное поле {ax, ay} параметрически зависящее от координат x, y на плоскости при z равном минимальному значению оси z. Длина и цвет векторов пропорциональна \sqrt{ax^2+ay^2}. Число рисуемых векторов зависит от meshnum. Вид стрелок/штрихов может быть изменён символами:
См. также flow, dew. См. Vect sample, для примеров кода и графика.
Это 3d версия графика. Здесь массивы ax, ay, az должны трёхмерными тензорами и длина вектора пропорциональна \sqrt{ax^2+ay^2+az^2}.
Рисует 3D векторное поле {ax, ay, az} параметрически зависящее от координат x, y, z. График рисуется на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). Длина и цвет векторов пропорциональна \sqrt{ax^2+ay^2+az^2}. Число рисуемых векторов зависит от meshnum. Вид стрелок/штрихов может быть изменён символами:
См. также vect, flow, dew. См. Vect sample, для примеров кода и графика.
Рисует капли для векторного поля {ax, ay}, параметрически зависящего от координат x, y при z равном минимальному значению оси z. Замечу, что график требует много памяти и процессорного времени для своего создания! Цвет капель пропорционален \sqrt{ax^2+ay^2}. Число капель определяется meshnum. См. также vect. См. Dew sample, для примеров кода и графика.
Рисует нити тока для векторного поля {ax, ay}, параметрически зависящего от координат x, y на плоскости при z равном минимальному значению оси z. Число нитей пропорционально значению опции value
(по умолчанию 5). Цвет нитей пропорционален \sqrt{ax^2+ay^2}. Строка sch может содержать
См. также pipe, vect, tape, barwidth. См. Flow sample, для примеров кода и графика.
Это 3d версия графика. Здесь массивы должны трёхмерными тензорами и цвет пропорционален \sqrt{ax^2+ay^2+az^2}.
x0 y0
udat vdat ['sch'='']x0 y0
xdat ydat udat vdat ['sch'='']Аналогично flow, но рисует одну нить из точки p0={x0,y0,z0}.
x0 y0 z0
udat vdat wdat ['sch'='']x0 y0 z0
xdat ydat zdat udat vdat wdat ['sch'='']Это 3d версия графика.
Рисует линии градиента скалярного поля phi[i,j] (или phi[i,j,k] в 3d случае) заданного параметрически {x[i,j,k], y[i,j,k], z[i,j,k]}. Число линий пропорционально значению опции value
(по умолчанию 5). См. также dens, cont, flow.
r0=0.05
]r0=0.05
]Рисует трубки тока для векторного поля {ax, ay}, параметрически зависящего от координат x, y на плоскости при z равном минимальному значению оси z. Число трубок пропорционально значению опции value
. Цвет и радиус трубок пропорционален \sqrt{ax^2+ay^2}. Тёплые цвета соответствуют нормальному току (типа стока). Холодные цвета соответствуют обратному току (типа источника). Параметр r0 задает радиус трубок. При r0<0 радиус трубок обратно пропорционален их амплитуде. См. также flow, vect. См. Pipe sample, для примеров кода и графика.
r0=0.05
]r0=0.05
]Это 3d версия графика. Здесь массивы ax, ay, az должны трёхмерными тензорами и цвет пропорционален \sqrt{ax^2+ay^2+az^2}.
Next: Nonlinear fitting, Previous: Vector fields, Up: MathGL core [Contents][Index]
Это функции, не относящиеся к какой-то специальной категории. Сюда входят функции построения графиков по текстовым формулам (FPlot и FSurf), рисования поверхностей из треугольников и четырёхугольников (TriPlot, TriCont, QuadPlot), произвольных точек в пространстве (Dots) и реконструкции по ним поверхности (Crust), графики плотности и линии уровня на плоскостях, перпендикулярных осям x, y или z (Dens[XYZ], Cont[XYZ], ContF[XYZ]). Каждый тип графика имеет похожий интерфейс. Есть версия для рисования одного массива с автоматическими координатами и версия для параметрически заданного массива. Параметры цветовой схемы задаются строкой. See Color scheme.
sval=nan
]sval=nan
]sval=nan
]Эти функции рисуют график плотности на x, y или z плоскостях. Если a – 3d массив, то выполняется интерполяция к заданному срезу sVal. Функции полезны для создания проекций 3D массивов на оси координат. См. также ContXYZ, ContFXYZ, dens, Data manipulation. См. Dens projection sample, для примеров кода и графика.
sval=nan
]sval=nan
]sval=nan
]Эти функции рисуют линии уровня на x, y или z плоскостях. Если a – 3d массив, то выполняется интерполяция к заданному срезу sVal. Опция value
задает число контуров. Функции полезны для создания проекций 3D массивов на оси координат. См. также ContFXYZ, DensXYZ, cont, Data manipulation. См. Cont projection sample, для примеров кода и графика.
sval=nan
]sval=nan
]sval=nan
]Эти функции рисуют закрашенные контуры уровня на x, y или z плоскостях. Если a – 3d массив, то выполняется интерполяция к заданному срезу sVal. Опция value
задает число контуров. Функции полезны для создания проекций 3D массивов на оси координат. См. также ContFXYZ, DensXYZ, cont, Data manipulation. См. ContF projection sample, для примеров кода и графика.
Рисует функцию ‘eqY(x)’ в плоскости z равно минимальному значению оси z с координатой ‘x’ в диапазоне осей координат. Опция value
задает начальное число точек. См. также plot.
Рисует параметрическую кривую {‘eqX(t)’, ‘eqY(t)’, ‘eqZ(t)’}, где координата ‘t’ меняется в диапазоне [0, 1]. Опция value
задает начальное число точек. См. также plot.
Рисует поверхность ‘eqY(x,y)’ с координатами ‘x’, ‘y’ в диапазоне xrange, yrange
. Опция value
задает число точек. См. также surf.
Рисует параметрическую поверхность {‘eqX(u,v)’, ‘eqY(u,v)’, ‘eqZ(u,v)’}, где координаты ‘u’, ‘v’ меняются в диапазоне [0, 1]. Опция value
задает число точек. См. также surf.
Рисует поверхность из треугольников. Вершины треугольников задаются индексами id в массиве точек {x[i], y[i], z[i]}. Строка sch задает цветовую схему. Если строка содержит ‘#’, то рисуется сетчатая поверхность. Размер по 1-му индексу массива id должен быть 3 или больше. Массивы x, y, z должны иметь одинаковые размеры. Массив c задает цвет треугольников (если id.ny=c.nx) или цвет вершин (если x.nx=c.nx). См. также dots, crust, quadplot, triangulation. См. TriPlot and QuadPlot, для примеров кода и графика.
Рисует линии уровня поверхности из треугольников при z=v[k] (или при z равном минимальному значению оси z если sch содержит ‘_’). Вершины треугольников задаются индексами id в массиве точек {x[i], y[i], z[i]}. Если аргуент v не задан, то используется массив из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7). Строка sch задает цветовую схему. Размер по 1-му индексу массива id должен быть 3 или больше. Массивы x, y, z должны иметь одинаковые размеры. Массив c задает цвет треугольников (если id.ny=c.nx) или цвет вершин (если x.nx=c.nx). См. также triplot, cont, triangulation.
Рисует поверхность из четырёхугольников. Вершины четырёхугольников задаются индексами id в массиве точек {x[i], y[i], z[i]}. Строка sch задает цветовую схему. Если строка содержит ‘#’, то рисуется сетчатая поверхность. Размер по 1-му индексу массива id должен быть 4 или больше. Массивы x, y, z должны иметь одинаковые размеры. Массив c задает цвет четырёхугольников (если id.ny=c.nx) или цвет вершин (если x.nx=c.nx). См. также triplot. См. TriPlot and QuadPlot, для примеров кода и графика.
Рисует произвольно расположенные точки {x[i], y[i], z[i]}. Строка sch задает цветовую схему и тип маркеров. Если определёны массивы c, a то они задают цвет и прозрачность точек соответственно. Непрозрачные точки с заданным цветом можно нарисовать с помощью tens, используя стиль ‘ .’. Массивы x, y, z, a должны иметь одинаковые размеры. См. также crust, tens, mark, plot. См. Dots sample, для примеров кода и графика.
Реконструирует и рисует поверхность по произвольно расположенным точкам {x[i], y[i], z[i]}. Опция value задает радиус ошибки (увеличите для удаления дыр). Строка sch задает цветовую схему. Если строка содержит ‘#’, то рисуется сетчатая поверхность. Массивы x, y, z должны иметь одинаковые размеры. См. также dots, triplot.
Next: Data manipulation, Previous: Other plotting, Up: MathGL core [Contents][Index]
Эти функции подбирают параметры функции для наилучшей аппроксимации данных, т.е. минимизируют сумму \sum_i (f(x_i, y_i, z_i) - a_i)^2/s_i^2. При этом аппроксимирующая функция ‘f’ может зависеть от одного аргумента ‘x’ (1D случай), от двух аргументов ‘x,y’ (2D случай) или от трех аргументов ‘x,y,z’ (3D случай). Функция ‘f’ также может зависеть от параметров. Список параметров задается строкой var (например, ‘abcd’). Обычно пользователь должен предоставить начальные значения параметров в переменной ini. Однако, при его отсутствии используются нулевые значения. Параметр print=true
включает вывод найденной формулы в Message (см. Error handling).
Функции Fit() и FitS() не рисуют полученные массивы. Они заполняют массив fit по формуле ‘f’ с найденными коэффициентами и возвращают \chi^2 ошибку аппроксимации. При этом, координаты ‘x,y,z’ равно распределены в диапазоне осей координат. Число точек в fit определяется опцией value
(по умолчанию mglFitPnts=100). Функции используют библиотеку GSL. См. Nonlinear fitting hints, для примеров кода и графика.
"Подгоняют" формулу вдоль x-, y- и z-направлений для 3d массива заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) с весовым множителем s[i,j,k].
"Подгоняют" формулу вдоль x-, y- и z-направлений для 3d массива заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) с весовым множителем 1.
x y
['pre'='' 'fnt'='' size=-1
]Печатает последнюю подобранную формулу с найденными коэффициентами в точке p0. Строка prefix будет напечатана перед формулой. Все другие параметры такие же как в Text printing.
Previous: Nonlinear fitting, Up: MathGL core [Contents][Index]
Создают распределения данных. Они не рисуют данные. Функции могут быть полезны в случае когда данные пользователя определены на случайно расположенных точка (например, после PIC расчетов) и он хочет построить график, требующий регулярных данных (данных на сетках). Диапазон сеток равен диапазону осей координат. Массивы x, y, z определяют положение (координаты) точек. Массив a задает значения данных. Число точек в результате res определяется опцией value
(по умолчанию mglFitPnts=100).
Заполняют значения массива ‘u’ в соответствии с формулой в строке eq. Формула – произвольное выражение, зависящее от переменных ‘x’, ‘y’, ‘z’, ‘u’, ‘v’, ‘w’. Координаты ‘x’, ‘y’, ‘z’ полагаются в диапазоне изменения осей координат. Переменная ‘u’ – значение исходного массива. Переменные ‘v’ и ‘w’ – значения массивов v, w, которые могут быть NULL
(т.е. могут быть опущены).
Заполняет значения массива ‘u’ результатом линейной интерполяции по триангулированной поверхности, найденной по произвольно расположенным точкам ‘x’, ‘y’, ‘z’. NAN значение используется для точек сетки вне триангулированной поверхности. См. Making regular data, для примеров кода и графика.
Заполняет значениями интерполяции массива v в точках {x, y, z}={X[i], Y[j], Z[k]
} (или {x, y, z}={X[i,j,k], Y[i,j,k], Z[i,j,k]
} если x, y, z не 1d массивы), где X,Y,Z
равномерно распределены в диапазоне осей координат и имеют такой же размер как и массив dat. Если параметр sl равен 0 или положительный, то изменятся будет только sl-ый срез.
dz=0.1 k0=100
]Решает уравнение в частных производных du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], где p=-i/k0*d/dx, q=-i/k0*d/dy – псевдо-дифференциальные оперторы. Параметры ini_re, ini_im задают действительную и мнимую часть начального распределения поля. Координаты ‘x’, ‘y’, ‘z’ полагаются в диапазоне изменения осей координат. Отмечу, ято в действительности этот диапазон увеличен на 3/2 для уменьшения отражения от границ сетки. Параметр dz задает шаг по эволюционной координате z. Сейчас используется упрощенный вид функции ham – исключены все “смешанные” члены (типа ‘x*p’->x*d/dx). Например, в 2D случае это функция вида ham = f(p,z) + g(x,z,u). Однако, коммутирующие члены (типа ‘x*q’->x*d/dy) разрешены. Переменная ‘u’ используется для амплитуды поля |u|, что позволяет решать нелинейные задачи – например уравнение Шредингера ham="p^2 + q^2 - u^2"
. Вы можете задавать мнимую часть для поглощения волн, например ham = "p^2 + i*x*(x>0)"
, но только для линейной зависимости от переменной ‘i’ (т.е. ham = hre+i*him). См. PDE solving hints, для примеров кода и графика.
Next: Examples, Previous: MathGL core, Up: Top [Contents][Index]
В данной главе описываются команды для работы с массивами данных. Они включают команды для выделения памяти и изменения размера данных, чтения данных из файла, численного дифференцирования, интегрирования, интерполяции и пр., заполнения по текстовой формуле и т.д. Класс позволяет работать с данными размерности не более 3 (как функции от трёх переменных – x,y,z). Массивы которые могут быть созданы командами MGL отображаются Small Caps шрифтом (например, DAT).
• Public variables: | ||
• Data constructor: | ||
• Data resizing: | ||
• Data filling: | ||
• File I/O: | ||
• Make another data: | ||
• Data changing: | ||
• Interpolation: | ||
• Data information: | ||
• Operators: | ||
• Global functions: | ||
• Evaluate expression: | ||
• Special data classes: |
Next: Data constructor, Up: Data processing [Contents][Index]
MGL не поддерживает прямой доступ к элементам массива. См. раздел Data filling
Next: Data resizing, Previous: Public variables, Up: Data processing [Contents][Index]
There are many functions, which can create data for output (see Data filling, File I/O, Make another data, Global functions). Here I put most useful of them.
nx=1
'eq']nx ny
['eq']nx ny nz
['eq']Выделяет память для массива данных и заполняет её нулями. Если указана формула eq, то данные заполняются также как при использовании fill.
val
Копирует данные из другого экземпляра данных. Если указана формула eq, то данные заполняются также как при использовании fill.
Читает данные из текстового файла с автоматическим определением размеров массива.
Удаляет массив данных из памяти.
Next: Data filling, Previous: Data constructor, Up: Data processing [Contents][Index]
nx=1 ny=1 nz=1
]Создает/пересоздает массив данных указанного размера и заполняет его нулями. Ничего не делает при mx, my, mz отрицательных или равных нулю.
mx [my=0 mz=0]
Изменяет размерность данных без изменения самого массива данных, так что результирующий массив mx*my*mz < nx*ny*nz. Если один из параметров my или mz ноль, то он будет выбран оптимальным образом. Например, если my=0, то будет my=nx*ny*nz/mx и mz=1.
Транспонирует (меняет порядок размерностей) массив данных. Новый порядок размерностей задается строкой dim. Функция может быть полезна для транспонирования одномерных (или квазиодномерных) массивов после чтения их из файла.
n1 [n2=0]
Увеличивает размер данных путем вставки (|n1|+1) новых срезов после (для n1>0) или перед (для n1<0) существующими данными. Можно добавить сразу 2 размерности для 1d массива, используя второй параметр n2. Данные в новые срезы будут скопированы из существующих. Например, для n1>0 новый массив будет a_ij^new = a_i^old where j=0...n1. Соответственно, для n1<0 новый массив будет a_ij^new = a_j^old, где i=0...|n1|.
rx [ry=1 rz=1 sm=off]
Уменьшает размер данных путём удаления элементов с индексами не кратными rx, ry, rz соответственно. Параметр smooth задает использовать сглаживания (т.е. out[i]=\sum_{j=i,i+r} a[j]/r) или нет (т.е. out[i]=a[j*r]).
n1 n2
'dir'Обрезает границы данных при i<n1 и i>n2 (при n2>0) или i>n[xyz]
-n2 (при n2<=0) вдоль направления dir.
[pos=off num=0]
Вставляет num срезов вдоль направления dir с позиции pos и заполняет их нулями.
[pos=off num=0]
Удаляет num срезов вдоль направления dir с позиции pos.
idx [idy=-1]
Сортирует строки (или срезы в 3D случае) по значениям в указанной колонке idx (или ячейках {idx,idy} для 3D случая). Не используйте в многопоточных функциях!
idx
Удаляет строки в которых значения для заданной колонки idx совпадают со значениями в следующей строке.
Объединяет данные из массива vdat с данными массива dat. При этом, функция увеличивает размер массива dat: в z-направлении для массивов с одинаковыми размерами по x и y; в y-направлении для массивов с одинаковыми размерами по x; в x-направлении в остальных случаях.
Next: File I/O, Previous: Data resizing, Up: Data processing [Contents][Index]
v1 ...
Создает новый массив данных dat и заполняет его числовыми значениями аргументов v1 ...
. Команда может создавать одно- и двухмерные массивы с произвольными значениями. Для создания 2d массива следует использовать разделитель ‘|’, который означает начало новой строки данных. Размер массива данных будет [maximal of row sizes * number of rows]. Например, команда list 1 | 2 3
создаст массив [1 0; 2 3]. Замечу, что максимальное число аргументов равно 1000.
Создает новый массив данных dat и заполняет его значениями из массивов d1 .... Команда может создавать двух- и трёхмерные (если аргументы – двумерные массивы) массивы. Меньшая размерность всех массивов в аргументах должна совпадать. В противном случае аргумент (массив) будет пропущен.
num v1 [v2=nan]
Создает новый одномерный массив данных dat размером num, и заполняет его равномерно в диапазоне [v1, v2]. Если v2=nan
, то используется v2=v1.
Заполняет значениями равно распределёнными в диапазоне [x1, x2] в направлении dir={‘x’,‘y’,‘z’}.
Заполняет значениями вычисленными по формуле eq. Формула представляет собой произвольное выражение, зависящее от переменных ‘x’, ‘y’, ‘z’, ‘u’, ‘v’, ‘w’. Координаты ‘x’, ‘y’, ‘z’ полагаются меняющимися в диапазоне Min x Max (в отличие от функции Modify
). Переменная ‘u’ – значения исходного массива, переменные ‘v’, ‘w’ – значения массивов vdat, wdat. Последние могут быть NULL
, т.е. опущены.
dim=0
]Аналогично предыдущему с координатами ‘x’, ‘y’, ‘z’, меняющимися в диапазоне [0,1]. Если указан dim>0, то изменяются только слои >=dim.
Заполняет массив данных ’x’ или ’k’ значениями для преобразований Ханкеля (’h’) или Фурье (’f’).
Заполняет значения массива результатом линейной интерполяции (считая координаты равнораспределенными в диапазоне осей координат или в диапазоне [x1,x2]*[y1,y2]) по триангулированной поверхности, найденной по произвольно расположенным точкам ‘x’, ‘y’, ‘z’. NAN значение используется для точек сетки вне триангулированной поверхности. См. Making regular data, для примеров кода и графика.
val [i=: j=: k=:]
Присваивает значения (под-)массива dat[i, j, k] = val. Индексы i, j, k равные ‘-1’ задают значения val для всего диапазона соответствующего направления(ий). Например, Put(val,-1,0,-1);
задает a[i,0,j]=val для i=0...(nx-1), j=0...(nz-1).
i=: j=: k=:
]Копирует значения из массива v в диапазон значений данного массива. Индексы i, j, k равные ‘-1’ задают диапазон изменения значений в соответствующих направление(ях). Младшие размерности массива v должны быть больше выбранного диапазона массива. Например, Put(v,-1,0,-1);
присвоит a[i,0,j]=v.ny>nz ? v.a[i,j] : v.a[i], где i=0...(nx-1), j=0...(nz-1) и условие v.nx>=nx выполнено.
Заполняет значениями интерполяции массива v в точках {x, y, z}={X[i], Y[j], Z[k]
} (или {x, y, z}={X[i,j,k], Y[i,j,k], Z[i,j,k]
} если x, y, z не 1d массивы), где X,Y,Z
равномерно распределены в диапазоне [x1,x2]*[y1,y2]*[z1,z2] и имеют такой же размер как и заполняемый массив. Если параметр sl равен 0 или положительный, то изменятся будет только sl-ый срез.
Заполняет значениями глобального кубического сплайна для массива v в точках x=X[i]
, где X
равномерно распределен в диапазоне [x1,x2] и имеет такой же размер как и заполняемый массив. Если параметр sl равен 0 или положительный, то изменятся будет только sl-ый срез.
Задает названия ids для колонок массива данных. Строка должна содержать один символ ’a’...’z’ на колонку. Эти названия используются в функции column.
Next: Make another data, Previous: Data filling, Up: Data processing [Contents][Index]
Читает данные из текстового файла с разделителями символом пробела/табуляции с автоматическим определением размера массива. Двойной перевод строки начинает новый срез данных (по направлению z).
mx [my=1 mz=1]
Читает данные из текстового файла с заданными размерами. Ничего не делается если параметры mx, my или mz равны нулю или отрицательны.
dim=2
]Читает данные из текстового файла с размерами, указанными в первых dim числах файла. При этом переменная dim задает размерность (1d, 2d, 3d) данных.
v1 v2 [dv=1 slice=off]
Объединяет данные из нескольких текстовых файлов. Имена файлов определяются вызовом функции sprintf(fname,templ,val);
, где val меняется от from до to с шагом step. Данные загружаются один за другим в один и тот же срез данных (при as_slice=false
) или срез-за-срезом (при as_slice=true
).
[slice=off]
Объединяет данные из нескольких текстовых файлов, чьи имена удовлетворяют шаблону templ (например, templ="t_*.dat"
). Данные загружаются один за другим в один и тот же срез данных (при as_slice=false
) или срез-за-срезом (при as_slice=true
).
Читает файл fname построчно и каждую строку сканирует на соответствие шаблону templ. Полученные числа (обозначаются как ‘%g’ в шаблоне) сохраняются. См. Saving and scanning file, для примеров кода и графика.
Сохраняет весь массив данных при ns=-1
или только ns-ый срез в текстовый файл.
Сохраняет строку str в файл fname. Для параметра mode=‘a’ происходит добавление строки (по умолчанию): для mode=‘w’ файл будет перезаписан. См. Saving and scanning file, для примеров кода и графика.
Читает массив с именем dname из HDF5 или HDF4 файла fname. Функция ничего не делает если библиотека была собрана без поддержки HDF5|HDF4.
rewrite
=off
]Сохраняет массив под именем dname в HDF5 или HDF4 файл fname. Функция ничего не делает если библиотека была собрана без поддержки HDF5|HDF4.
Помещает имена массивов данных в HDF5 файле fname в строку buf разделёнными символом табуляции ’\t’. В версии MGL имена массивов будут выведены как сообщение. Функция ничего не делает если библиотека была собрана без поддержки HDF5.
v1=0 v2=1
]Читает данные из растрового файла. RGB значения пикселов преобразуются в число в диапазоне [v1, v2] используя цветовую схему sch (see Color scheme).
v1=0 v2=0
]Сохраняет данные в растровый файл. Числовые значения, нормированные в диапазон [v1, v2], преобразуются в RGB значения пикселов, используя цветовую схему sch (see Color scheme). Если v1>=v2, то значения v1, v2 определяются автоматически как минимальное и максимальное значение данных.
Next: Data changing, Previous: File I/O, Up: Data processing [Contents][Index]
xx [yy=: zz=:]
Возвращает в res подмассив массива данных dat с фиксированными значениями индексов с положительными значениями. Например, SubData(-1,2)
выделяет третью строку (индексы начинаются с нуля), SubData(4,-1)
выделяет 5-ую колонку, SubData(-1,-1,3)
выделяет 4-ый срез и т.д. В MGL скриптах обычно используется упрощенная версия dat(xx,yy,zz)
. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Возвращает в res подмассив массива данных dat с индексами, заданными в массивах xx, yy, zz (косвенная адресация). Результат будет иметь размерность массивов с индексами. Размеры массивов xx, yy, zz с индексами должна быть одинакова, либо должны быть "скаляром" (т.е. 1*1*1). В MGL скриптах обычно используется упрощенная версия dat(xx,yy,zz)
. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Возвращает массив данных заполненный по формуле eq, вычисленной для именованных колонок (или срезов). Например, Column("n*w^2/exp(t)");
. Имена колонок должны быть предварительно заданы функцией idset или при чтении файлов данных. В MGL скриптах обычно используется упрощенная версия dat('eq')
. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
mx [my=1 mz=1]
Возвращает массив данных размером mx, my, mz со значениями полученными интерполяцией значений из части [x1,x2] x [y1,y2] x [z1,z2] исходного массива. Величины x,y,z полагаются нормированными в диапазоне [0,1]. Если значение mx, my или mz равно 0, то исходный размер используется. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
norm=on
]norm=on
]norm=on
]Возвращает массив данных, полученный в результате интерполяции исходного массива в точках других массивов (например, res[i,j]=dat[idat[i,j],jdat[i,j]]). Размеры массивов idat, jdat, kdat должны совпадать. Координаты в idat, jdat, kdat полагаются нормированными в диапазон [0,1] (при norm=true
) или в диапазоны [0,nx], [0,ny], [0,nz] соответственно. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
val
'dir' [norm=on
]val
'dir' idat [norm=on
]Возвращает массив индексов (корней) вдоль выбранного направления dir в которых значения массива dat равны val. Выходной массив будет иметь размеры массива dat в направлениях поперечных dir. Если предоставлен массив idat, то его значения используются как стартовые при поиске. Это позволяет найти несколько веток с помощью последовательного вызова функции. Индексы полагаются нормированными в диапазон [0,1] (при norm=true
) или в диапазоны [0,nx], [0,ny], [0,nz] соответственно. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов. См. Solve sample, для примеров кода и графика.
ini
['var'='x']Возвращает массив корней уравнения ’func’=0 для переменной var с начальными положениями ini. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
num v1 v2 [nsub=0]
num v1 v2 [nsub=0]
Возвращает распределение (гистограмму) из n точек от значений массива в диапазоне [v1, v2]. Массив w задает веса элементов (по умолчанию все веса равны 1). Параметр nsub задает число дополнительных точек интерполяции (для сглаживания получившейся гистограммы). Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов. См. также Data manipulation
Возвращает момент (1d массив) данных вдоль направления dir. Строка how определяет тип момента. Момент определяется как res_k = \sum_ij how(x_i,y_j,z_k) a_ij/ \sum_ij a_ij если dir=‘z’ и т.д. Координаты ‘x’, ‘y’, ‘z’ – индексы массива в диапазоне [0,1]. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Возвращает результат суммирования данных вдоль направления(ий) dir. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Возвращает максимальное значение данных вдоль направления(ий) dir. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Возвращает минимальное значение данных вдоль направления(ий) dir. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Возвращает прямое произведение массивов (наподобие, res[i,j] = adat[i]*bdat[j] и т.д.). Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Возвращает массив диагональных элементов a[i,i] (для 2D данных) или a[i,i,i] (для 3D данных) где i=0...nx-1. В 1D случае возвращается сам массив данных. Размеры массива данных должен быть ny,nz >= nx или ny,nz = 1. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Возвращает корреляцию массивов a (или this в C++) и b вдоль направлений dir. При вычислении используется преобразование Фурье. Поэтому может потребоваться вызов функций swap и/или norm перед построением. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
Находит параметры импульса вдоль направления dir: максимальное значение (в колонке 0), его положение (в колонке 1), ширина по параболлической аппроксимации (в колонке 3) и по полувысоте (в колонке 2), энергию около максимума (в колонке 4). NAN значения используются для ширин если максимум расположен вблизи границ массива. Отмечу, что для комплексных массивов есть неопределенность определения параметров. Обычно следует использовать квадрат абсолютного значения амплитуды (т.е. |dat[i]|^2). Поэтому MathGL не включает эту функцию в mglDataC
, хотя формально C функция будет работать и для них, но будет использовать абсолютное значение амплитуды (т.е. |dat[i]|). Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов. См. также max, min, momentum, sum. См. Pulse properties, для примеров кода и графика.
Next: Interpolation, Previous: Make another data, Up: Data processing [Contents][Index]
These functions change the data in some direction like differentiations, integrations and so on. The direction in which the change will applied is specified by the string parameter, which may contain ‘x’, ‘y’ or ‘z’ characters for 1-st, 2-nd and 3-d dimension correspondingly.
Суммирует с накоплением в выбранном направлении(ях).
Выполняет интегрирование (методом трапеций) в выбранном направлении(ях).
Выполняет дифференцирование в выбранном направлении(ях).
Выполняет дифференцирование данных, параметрически зависящих от координат, в направлении x с y, z=constant. Параметр z может быть опущен, что соответствует 2D случаю. Используются следующие формулы (2D случай): da/dx = (a_j*y_i-a_i*y_j)/(x_j*y_i-x_i*y_j), где a_i=da/di, a_j=da/dj обозначает дифференцирование вдоль 1-ой и 2-ой размерности. Похожие формулы используются и в 3D случае. Порядок аргументов можно менять – например, если данные a(i,j) зависят от координат {x(i,j), y(i,j)}, то обычная производная по ‘x’ будет равна Diff(x,y);
, а обычная производная по ‘y’ будет равна Diff(y,x);
.
Выполняет двойное дифференцирование (как в операторе Лапласа) в выбранном направлении(ях).
Выполняет синус преобразование в выбранном направлении(ях). Синус преобразование есть \sum a_j \sin(k j) (см. http://en.wikipedia.org/wiki/Discrete_sine_transform#DST-I).
Выполняет косинус преобразование в выбранном направлении(ях). Синус преобразование есть \sum a_j \cos(k j) (см. http://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-I).
Выполняет преобразование Ханкеля в выбранном направлении(ях). Преобразование Ханкеля есть \sum a_j J_0(k j) (см. http://en.wikipedia.org/wiki/Hankel_transform).
k
Выполняет преобразование wavelet в выбранном направлении(ях). Параметр dir задает тип: ‘d’ для daubechies, ‘D’ для центрированного daubechies, ‘h’ для haar, ‘H’ для центрированного haar, ‘b’ для bspline, ‘B’ для центрированного bspline. Если указан символ ‘i’, то выполняется обратное преобразование. Параметр k задает размер преобразования.
Меняет местами левую и правую части данных в выбранном направлении(ях). Полезно для отображения результата FFT.
Сдвигает данные на num ячеек в выбранном направлении(ях). Соответствует замене индекса на i->(i+num)%nx при dir='x'
.
Отражает данные в выбранном направлении(ях). Соответствует замене индекса на i->n-i. Отмечу, что похожего эффекта на графике можно достичь используя опции (see Command options), например, surf dat; xrange 1 -1
.
da=2*pi
]Удаляет скачки данных (например, скачки фазы после обратных тригонометрических функций) с периодом da в выбранном направлении(ях).
type
['dir'='xyz']Сглаживает данные в выбранном направлении(ях) dir. Строка dirs задает направления вдоль которых будет производиться сглаживание. Если dirs содержит: ‘0’ – ничего не делает, ‘3’ линейное усреднение по 3 точкам, ‘5’ линейное усреднение по 5 точкам. Если dir содержит символы ‘dN’ (где ‘N’ – цифра 1,2,...,9), то используется линейное усреднение по (2*N+1)-ой точке. По умолчанию используется квадратичное усреднение по 5 точкам.
Находит огибающую данных в выбранном направлении dir.
q
Вычисляет один шаг диффракции в конечно-разностной схеме с параметром q=\delta t/\delta x^2 используя метод третьего порядка точности. Параметр how может содержать:
v1 v2 [sym=off dim=0]
Нормирует данные в интервал [v1,v2]. Если sym=true
, то используется симметричный интервал [-max(|v1|,|v2|), max(|v1|,|v2|)]. Изменения применяются только к срезам >=dim.
v1 v2
['dir'='z' keep=on sym=off
]Нормирует данные срез-за-срезом в выбранном направлении dir в интервал [v1,v2]. Если sym=true
, то используется симметричный интервал [-max(|v1|,|v2|), max(|v1|,|v2|)]. Если keep=true
, то максимальное значение k-го среза ограничено величиной
\sqrt{\sum a_ij(k)/\sum a_ij(0)}.
val
Ограничивает амплитуду данных диапазоном [-val,val]. При этом сохраняется исходный знак (фаза для комплексных чисел). Эквивалентно операции a[i] *= abs(a[i])<val?1.:val/abs(a[i]);
.
Next: Data information, Previous: Data changing, Up: Data processing [Contents][Index]
Скрипты MGL могут использовать интерполяцию кубическими сплайнами с помощью команд evaluate или refill. Также можно использовать resize для массива с новыми размерами.
Next: Operators, Previous: Interpolation, Up: Data processing [Contents][Index]
В MathGL есть ряд функций для получения свойств массива данных. В MGL скриптах большинство из них реализовано в виде "суффиксов". Суффиксы дают числовое значение некоторой характеристики массива данных. Например, его размер, минимальное и максимальное значение, сумму элементов и т.д. Суффиксы начинаются с точки ‘.’ сразу после массива (без пробелов). Например, a.nx
даст размер массива a вдоль x, b(1).max
даст максимальное значение второй колонки массива b, (c(:,0)^2).sum
даст сумму квадратов в первой строке массива c и т.д.
Возвращает строку с информацией о данных (размеры, моменты и пр.) или пишет её в файл. В MGL скрипте печатает её как сообщение.
Печатает строку txt как сообщение.
Печатает значение числа val как сообщение.
Аналогично info, но сразу выводит в stdout.
Печатает все значения массива dat как сообщение.
Возвращает размер данных в направлении x, y и z соответственно.
Возвращает максимальное значение массива данных.
Возвращает минимальное значение массива данных.
Возвращает минимальное значение массива данных и его приближенное (интерполированное) положение в переменные x, y, z.
Возвращает нулевой момент (энергию, I=\sum a_i) и записывает первый (среднее, m = \sum \xi_i a_i/I), второй (ширину, w^2 = \sum (\xi_i-m)^2 a_i/I), третий (асимметрия, s = \sum (\xi_i-m)^3 a_i/ I w^3) и четвёртый моменты (эксцесс, k = \sum (\xi_i-m)^4 a_i / 3 I w^4)). Здесь \xi – соответствующая координата если dir равно ‘'x'’, ‘'y'’, ‘'z'’. В противном случае среднее, ширина, асимметрия, эксцесс равны m = \sum a_i/N, w^2 = \sum (a_i-m)^2/N и т.д.
Находит положение (после заданного в i, j, k) первого не нулевого значения формулы cond. Функция возвращает найденное значение и записывает его положение в i, j, k.
Находит положение (перед заданного в i, j, k) последнего не нулевого значения формулы cond. Функция возвращает найденное значение и записывает его положение в i, j, k.
Возвращает первое число массива (для .a
это dat->a[0]
).
Next: Global functions, Previous: Data information, Up: Data processing [Contents][Index]
Копирует данные из другого экземпляра.
val
Устанавливает все значения массива равными val.
val
Поэлементно умножает на массив d или на число val.
val
Поэлементно делит на массив d или на число val.
val
Поэлементно прибавляет d или число val.
val
Поэлементно вычитает d или число val.
Next: Evaluate expression, Previous: Operators, Up: Data processing [Contents][Index]
Выполняет интегральное преобразование комплексных данных real, imag в выбранном направлении и возвращает модуль результата. Порядок и тип преобразований задается строкой type: первый символ для x-направления, второй для y-направления, третий для z-направления. Возможные символы: ‘f’ – прямое преобразование Фурье, ‘i’ – обратное преобразование Фурье, ‘s’ – синус преобразование, ‘c’ – косинус преобразование, ‘h’ – преобразование Ханкеля, ‘n’ или ‘ ’ – нет преобразования.
Аналогично предыдущему с заданными амплитудой ampl и фазой phase комплексных чисел.
Выполняет Фурье преобразование для комплексных данных re+i*im в направлениях dir. Результат помещается обратно в массивы re и im.
dn
['dir'='x']Выполняет оконное преобразование Фурье длиной dn для комплексных данных real, imag и возвращает модуль результата. Например, для dir=‘x’ результат будет иметь размер {int(nx/dn), dn, ny} и будет равен res[i,j,k]=|\sum_d^dn exp(I*j*d)*(real[i*dn+d,k]+I*imag[i*dn+d,k])|/dn.
Возвращает решение трехдиагональной системы уравнений A[i]*x[i-1]+B[i]*x[i]+C[i]*x[i+1]=D[i]. Строка how может содержать:
Размеры массивов A, B, C должны быть одинаковы. Также их размерности должны совпадать со всеми или с "младшими" размерностями массива D. См. PDE solving hints, для примеров кода и графика.
dz=0.1 k0=100
]Решает уравнение в частных производных du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], где p=-i/k0*d/dx, q=-i/k0*d/dy – псевдо-дифференциальные операторы. Параметры ini_re, ini_im задают начальное распределение поля. Координаты в уравнении и в решении полагаются в диапазоне осей координат. Замечу, что внутри этот диапазон увеличивается в 3/2 раза для уменьшения отражения от границ расчетного интервала. Параметр dz задает шаг по эволюционной координате z. В данный момент использован упрощенный алгоритм, когда все “смешанные” члена (типа ‘x*p’->x*d/dx) исключаются. Например, в 2D случае это функции типа ham = f(p,z) + g(x,z,u). При этом допускаются коммутирующие комбинации (типа ‘x*q’->x*d/dy). Переменная ‘u’ используется для обозначения амплитуды поля |u|. Это позволяет решать нелинейные задачи – например, нелинейное уравнение Шредингера ham='p^2+q^2-u^2'
. Также можно указать мнимую часть для поглощения (типа ham = 'p^2+i*x*(x>0)'
), но только если зависимость от ‘i’ линейная, т.е. ham = hre+i*him. См. PDE solving hints, для примеров кода и графика.
x0 y0 z0 p0 q0 v0 [dt=0.1 tmax=10]
Решает систему геометрооптических уравнений dr/dt = d ham/dp, dp/dt = -d ham/dr. Это гамильтоновы уравнения для траектории частицы в 3D случае. Гамильтониан ham может зависеть от координат ‘x’, ‘y’, ‘z’, импульсов ‘p’=px, ‘q’=py, ‘v’=pz и времени ‘t’: ham = H(x,y,z,p,q,v,t). Начальная точка (при t=0
) задается переменными {x0, y0, z0, p0, q0, v0}. Параметры dt и tmax задают шаг и максимальное время интегрирования. Результат – массив {x,y,z,p,q,v,t} с размером {7 * int(tmax/dt+1) }.
dt=0.1 tmax=10
]Решает систему обыкновенных дифференциальных уравнений dx/dt = df(x). Функции df могут быть заданны строкой с разделенными ’;’ формулами (аргумент var задает символы для переменных x[i]) или указателем на функцию, которая заполняет dx
по заданным значениям x
. Параметры ini, dt, tmax задают начальные значения, шаг и максимальное время интегрирования. Результат – массив с размером {n * int(tmax/dt+1)}.
r=1 k0=100
xx yy]Решает уравнение в частных производных du/dt = i*k0*ham(p,q,x,y,|u|)[u] в сопровождающей системе координат, где p=-i/k0*d/dx, q=-i/k0*d/dy – псевдо-дифференциальные операторы. Параметры ini_re, ini_im задают начальное распределение поля. Параметр ray задает опорный луч для сопровождающей системы координат. Можно использовать луч найденный с помощью ray. Опорный луч должен быть достаточно гладкий, чтобы система координат была однозначной и для исключения ошибок интегрирования. Если массивы xx и yy указаны, то в них записываются декартовы координаты для каждой точки найденного решения. См. также pde, qo3d. См. PDE solving hints, для примеров кода и графика.
r=1 k0=100
xx yy zz]Решает уравнение в частных производных du/dt = i*k0*ham(p,q,v,x,y,z,|u|)[u] в сопровождающей системе координат, где p=-i/k0*d/dx, q=-i/k0*d/dy, v=-i/k0*d/dz – псевдо-дифференциальные операторы. Параметры ini_re, ini_im задают начальное распределение поля. Параметр ray задает опорный луч для сопровождающей системы координат. Можно использовать луч найденный с помощью ray. Опорный луч должен быть достаточно гладкий, чтобы система координат была однозначной и для исключения ошибок интегрирования. Если массивы xx, yy и zz указаны, то в них записываются декартовы координаты для каждой точки найденного решения. См. также pde, qo2d.
Вычисляет якобиан преобразования {i,j,k} в {x,y,z}, где координаты {i,j,k} полагаются нормированными в интервал [0,1]. Якобиан находится по формуле det||dr_\alpha/d\xi_\beta||, где r={x,y,z} и \xi={i,j,k}. Все размерности всех массивов должны быть одинаковы. Данные должны быть трехмерными если указаны все 3 массива {x,y,z} или двумерными если только 2 массива {x,y}.
Выполняет триангуляцию для произвольно расположенных точек с координатами {x,y,z} (т.е. находит треугольники, соединяющие точки). Первая размерность всех массивов должна быть одинакова x.nx=y.nx=z.nx
. Получившийся массив можно использовать в triplot или tricont для визуализации реконструированной поверхности. См. Making regular data, для примеров кода и графика.
num
[skip=20
]Находит num точек {x[i]=res[0,i], y[i]=res[1,i]} фрактала с использованием итерационной системы функций (IFS). Матрица dat используется для генерации в соответствии с формулами
x[i+1] = dat[0,i]*x[i] + dat[1,i]*y[i] + dat[4,i]; y[i+1] = dat[2,i]*x[i] + dat[3,i]*y[i] + dat[5,i];
Значение dat[6,i]
– весовой коэффициент для i-ой строки матрицы dat. Первые skip итераций будут опущены. Массив dat должен иметь размер по x больше или равный 7. См. IFS sample, для примеров кода и графика.
num
[skip=20
]Находит num точек {x[i]=res[0,i], y[i]=res[1,i], z[i]=res[2,i]} фрактала с использованием итерационной системы функций (IFS). Матрица dat используется для генерации в соответствии с формулами
x[i+1] = dat[0,i]*x[i] + dat[1,i]*y[i] + dat[2,i]*z[i] + dat[9,i]; y[i+1] = dat[3,i]*x[i] + dat[4,i]*y[i] + dat[5,i]*z[i] + dat[10,i]; z[i+1] = dat[6,i]*x[i] + dat[7,i]*y[i] + dat[8,i]*z[i] + dat[10,i];
Значение dat[6,i]
– весовой коэффициент для i-ой строки матрицы dat. Первые skip итераций будут опущены. Массив dat должен иметь размер по x больше или равный 13. См. IFS sample, для примеров кода и графика.
num
[skip=20
]Считывает параметры фрактала name из файла fname и находит num точек для него. Первые skip итераций будут опущены. См. также ifs2d, ifs3d.
Файл IFS может содержать несколько записей. Каждая запись содержит имя фрактала (‘binary’ в примере ниже) и тело в фигурных скобках {} с параметрами фрактала. Символ ‘;’ начинает комментарий. Если имя содержит ‘(3D)’ или ‘(3d)’, то определен 3d IFS фрактал. Пример содержит два фрактала: ‘binary’ – обычный 2d фрактал, и ‘3dfern (3D)’ – 3d фрактал.
binary { ; comment allowed here ; and here .5 .0 .0 .5 -2.563477 -0.000003 .333333 ; also comment allowed here .5 .0 .0 .5 2.436544 -0.000003 .333333 .0 -.5 .5 .0 4.873085 7.563492 .333333 } 3dfern (3D) { .00 .00 0 .0 .18 .0 0 0.0 0.00 0 0.0 0 .01 .85 .00 0 .0 .85 .1 0 -0.1 0.85 0 1.6 0 .85 .20 -.20 0 .2 .20 .0 0 0.0 0.30 0 0.8 0 .07 -.20 .20 0 .2 .20 .0 0 0.0 0.30 0 0.8 0 .07 }
Next: Special data classes, Previous: Global functions, Up: Data processing [Contents][Index]
В MGL скриптах в качестве аргументов команд можно использовать произвольные формулы от существующих массивов данных и констант. Есть только 2 ограничения: формула не должна содержать пробелов (чтобы распознаваться как один аргумент), формула не может быть аргументом, который может быть пересоздан при выполнении скрипта.
Previous: Evaluate expression, Up: Data processing [Contents][Index]
MGL использует специальные классы автоматически.
Next: Symbols and hot-keys, Previous: Data processing, Up: Top [Contents][Index]
This chapter contain information about basic and advanced MathGL, hints and samples for all types of graphics. I recommend you read first 2 sections one after another and at least look on Hints section. Also I recommend you to look at General concepts and FAQ.
Most of sample scripts placed below use a set of functions for preparing the data.
func 'prepare1d' new y 50 3 modify y '0.7*sin(2*pi*x)+0.5*cos(3*pi*x)+0.2*sin(pi*x)' modify y 'sin(2*pi*x)' 1 modify y 'cos(2*pi*x)' 2 new x1 50 'x' new x2 50 '0.05-0.03*cos(pi*x)' new y1 50 '0.5-0.3*cos(pi*x)' new y2 50 '-0.3*sin(pi*x)' return func 'prepare2d' new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' return func 'prepare3d' new c 61 50 40 '-2*(x^2+y^2+z^4-z^2)+0.2' new d 61 50 40 '1-2*tanh((x+y)*(x+y))' return func 'prepare2v' new a 20 30 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' new b 20 30 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' return func 'prepare3v' define $1 pow(x*x+y*y+(z-0.3)*(z-0.3)+0.03,1.5) define $2 pow(x*x+y*y+(z+0.3)*(z+0.3)+0.03,1.5) new ex 10 10 10 '0.2*x/$1-0.2*x/$2' new ey 10 10 10 '0.2*y/$1-0.2*y/$2' new ez 10 10 10 '0.2*(z-0.3)/$1-0.2*(z+0.3)/$2' return
Basically, you can put this text after the script. Note, that you need to terminate main script by stop command before defining a function.
• Basic usage: | ||
• Advanced usage: | ||
• Data handling: | ||
• Data plotting: | ||
• 1D samples: | ||
• 2D samples: | ||
• 3D samples: | ||
• Vector field samples: | ||
• Hints: | ||
• FAQ: |
Next: Advanced usage, Up: Examples [Contents][Index]
MGL script can be used by several manners. Each has positive and negative sides:
Positive sides are possibilities to view the plot at once and to modify it, rotate, zoom or switch on transparency or lighting by hands or by mouse. Negative side is the needness of the X-terminal.
Positive aspects are: batch processing of similar data set, for example, a set of resulting data files for different calculation parameters), running from the console program, including the cluster calculation), fast and automated drawing, saving pictures for further analysis, or demonstration). Negative sides are: the usage of the external program for picture viewing. Also, the data plotting is non-visual. So, you have to imagine the picture, view angles, lighting and so on) before the plotting. I recommend to use graphical window for determining the optimal parameters of plotting on the base of some typical data set. And later use these parameters for batch processing in console program.
In this case you can use the program: mglconv
or mglview
for viewing.
You can easily execute MGL script within C/C++/Fortan code. This can be useful for fast data plotting, for example, in web applications, where textual string (MGL script) may contain all necessary information for plot. The basic C++ code may look as following
const char *mgl_script; // script itself, can be of type const wchar_t* mglGraph gr; mglParse pr; pr.Execute(&gr, mgl_script);
The simplest script is
box # draw bounding box axis # draw axis fplot 'x^3' # draw some function
Just type it in UDAV and press F5. Also you can save it in text file ‘test.mgl’ and type in the console mglconv test.mgl
what produce file ‘test.mgl.png’ with resulting picture.
Next: Data handling, Previous: Basic usage, Up: Examples [Contents][Index]
Now I show several non-obvious features of MGL: several subplots in a single picture, curvilinear coordinates, text printing and so on. Generally you may miss this section at first reading, but I don’t recommend it.
• Subplots: | ||
• Axis and ticks: | ||
• Curvilinear coordinates: | ||
• Colorbars: | ||
• Bounding box: | ||
• Ternary axis: | ||
• Text features: | ||
• Legend sample: | ||
• Cutting sample: |
Next: Axis and ticks, Up: Advanced usage [Contents][Index]
Let me demonstrate possibilities of plot positioning and rotation. MathGL has a set of functions: subplot, inplot, title, aspect and rotate and so on (see Subplots and rotation). The order of their calling is strictly determined. First, one changes the position of plot in image area (functions subplot, inplot and multiplot). Secondly, you can add the title of plot by title function. After that one may rotate the plot (command rotate). Finally, one may change aspects of axes (command aspect). The following code illustrates the aforesaid it:
subplot 2 2 0 box:text -1 1.1 'Just box' ':L' inplot 0.2 0.5 0.7 1 off box:text 0 1.2 'InPlot example' subplot 2 2 1:title 'Rotate only' rotate 50 60:box subplot 2 2 2:title 'Rotate and Aspect' rotate 50 60:aspect 1 1 2:box subplot 2 2 3:title 'Shear' box 'c':shear 0.2 0.1:box
Here I used function Puts
for printing the text in arbitrary position of picture (see Text printing). Text coordinates and size are connected with axes. However, text coordinates may be everywhere, including the outside the bounding box. I’ll show its features later in Text features.
Note that several commands can be placed in a string if they are separated by ‘:’ symbol.
More complicated sample show how to use most of positioning functions:
subplot 3 2 0:title 'StickPlot' stickplot 3 0 20 30:box 'r':text 0 0 0 '0' 'r' stickplot 3 1 20 30:box 'g':text 0 0 0 '1' 'g' stickplot 3 2 20 30:box 'b':text 0 0 0 '2' 'b' subplot 3 2 3 '':title 'ColumnPlot' columnplot 3 0:box 'r':text 0 0 '0' 'r' columnplot 3 1:box 'g':text 0 0 '1' 'g' columnplot 3 2:box 'b':text 0 0 '2' 'b' subplot 3 2 4 '':title 'GridPlot' gridplot 2 2 0:box 'r':text 0 0 '0' 'r' gridplot 2 2 1:box 'g':text 0 0 '1' 'g' gridplot 2 2 2:box 'b':text 0 0 '2' 'b' gridplot 2 2 3:box 'm':text 0 0 '3' 'm' subplot 3 2 5 '':title 'InPlot':box inplot 0.4 1 0.6 1 on:box 'r' multiplot 3 2 1 2 1 '':title 'MultiPlot and ShearPlot':box shearplot 3 0 0.2 0.1:box 'r':text 0 0 '0' 'r' shearplot 3 1 0.2 0.1:box 'g':text 0 0 '1' 'g' shearplot 3 2 0.2 0.1:box 'b':text 0 0 '2' 'b'
Next: Curvilinear coordinates, Previous: Subplots, Up: Advanced usage [Contents][Index]
MathGL library can draw not only the bounding box but also the axes, grids, labels and so on. The ranges of axes and their origin (the point of intersection) are determined by functions SetRange()
, SetRanges()
, SetOrigin()
(see Ranges (bounding box)). Ticks on axis are specified by function SetTicks
, SetTicksVal
, SetTicksTime
(see Ticks). But usually
Command axis draws axes. Its textual string shows in which directions the axis or axes will be drawn (by default "xyz"
, function draws axes in all directions). Command grid draws grid perpendicularly to specified directions. Example of axes and grid drawing is:
subplot 2 2 0:title 'Axis origin, Grid' origin 0 0:axis:grid:fplot 'x^3' subplot 2 2 1:title '2 axis' ranges -1 1 -1 1:origin -1 -1:axis ylabel 'axis_1':fplot 'sin(pi*x)' 'r2' ranges 0 1 0 1:origin 1 1:axis ylabel 'axis_2':fplot 'cos(pi*x)' subplot 2 2 3:title 'More axis' origin nan nan:xrange -1 1:axis xlabel 'x' 0:ylabel 'y_1' 0:fplot 'x^2' 'k' yrange -1 1:origin -1.3 -1:axis 'y' 'r' ylabel '#r{y_2}' 0.2:fplot 'x^3' 'r' subplot 2 2 2:title '4 segments, inverted axis':origin 0 0: inplot 0.5 1 0.5 1 on:ranges 0 10 0 2:axis fplot 'sqrt(x/2)':xlabel 'W' 1:ylabel 'U' 1 inplot 0 0.5 0.5 1 on:ranges 1 0 0 2:axis 'x' fplot 'sqrt(x)+x^3':xlabel '\tau' 1 inplot 0.5 1 0 0.5 on:ranges 0 10 4 0:axis 'y' fplot 'x/4':ylabel 'L' -1 inplot 0 0.5 0 0.5 on:ranges 1 0 4 0:fplot '4*x^2'
Note, that MathGL can draw not only single axis (which is default). But also several axis on the plot (see right plots). The idea is that the change of settings does not influence on the already drawn graphics. So, for 2-axes I setup the first axis and draw everything concerning it. Then I setup the second axis and draw things for the second axis. Generally, the similar idea allows one to draw rather complicated plot of 4 axis with different ranges (see bottom left plot).
At this inverted axis can be created by 2 methods. First one is used in this sample – just specify minimal axis value to be large than maximal one. This method work well for 2D axis, but can wrongly place labels in 3D case. Second method is more general and work in 3D case too – just use aspect function with negative arguments. For example, following code will produce exactly the same result for 2D case, but 2nd variant will look better in 3D.
# variant 1 ranges 0 10 4 0:axis # variant 2 ranges 0 10 0 4:aspect 1 -1:axis
Another MathGL feature is fine ticks tunning. By default (if it is not changed by SetTicks
function), MathGL try to adjust ticks positioning, so that they looks most human readable. At this, MathGL try to extract common factor for too large or too small axis ranges, as well as for too narrow ranges. Last one is non-common notation and can be disabled by SetTuneTicks
function.
Also, one can specify its own ticks with arbitrary labels by help of SetTicksVal
function. Or one can set ticks in time format. In last case MathGL will try to select optimal format for labels with automatic switching between years, months/days, hours/minutes/seconds or microseconds. However, you can specify its own time representation using formats described in http://www.manpagez.com/man/3/strftime/. Most common variants are ‘%X’ for national representation of time, ‘%x’ for national representation of date, ‘%Y’ for year with century.
The sample code, demonstrated ticks feature is
subplot 3 3 0:title 'Usual axis' axis subplot 3 3 1:title 'Too big/small range' ranges -1000 1000 0 0.001:axis subplot 3 3 2:title 'LaTeX-like labels' axis 'F!' subplot 3 3 3:title 'Too narrow range' ranges 100 100.1 10 10.01:axis subplot 3 3 4:title 'No tuning, manual "+"' axis '+!' # for version <2.3 you can use #tuneticks off:axis subplot 3 3 5:title 'Template for ticks' xtick 'xxx:%g':ytick 'y:%g' axis xtick '':ytick '' # switch it off for other plots subplot 3 3 6:title 'No tuning, higher precision' axis '!4' subplot 3 3 7:title 'Manual ticks' ranges -pi pi 0 2 xtick pi 3 '\pi' xtick 0.886 'x^*' on # note this will disable subticks drawing # or you can use #xtick -pi '\pi' -pi/2 '-\pi/2' 0 '0' 0.886 'x^*' pi/2 '\pi/2' pi 'pi' # or you can use #list v -pi -pi/2 0 0.886 pi/2 pi:xtick v '-\pi\n-\pi/2\n{}0\n{}x^*\n\pi/2\n\pi' axis:grid:fplot '2*cos(x^2)^2' 'r2' subplot 3 3 8:title 'Time ticks' xrange 0 3e5:ticktime 'x':axis
The last sample I want to show in this subsection is Log-axis. From MathGL’s point of view, the log-axis is particular case of general curvilinear coordinates. So, we need first define new coordinates (see also Curvilinear coordinates) by help of SetFunc
or SetCoor
functions. At this one should wary about proper axis range. So the code looks as following:
subplot 2 2 0 '<_':title 'Semi-log axis' ranges 0.01 100 -1 1:axis 'lg(x)' '' '' axis:grid 'xy' 'g':fplot 'sin(1/x)' xlabel 'x' 0:ylabel 'y = sin 1/x' 0 subplot 2 2 1 '<_':title 'Log-log axis' ranges 0.01 100 0.1 100:axis 'lg(x)' 'lg(y)' '' axis:grid '!' 'h=':grid:fplot 'sqrt(1+x^2)' xlabel 'x' 0:ylabel 'y = \sqrt{1+x^2}' 0 subplot 2 2 2 '<_':title 'Minus-log axis' ranges -100 -0.01 -100 -0.1:axis '-lg(-x)' '-lg(-y)' '' axis:fplot '-sqrt(1+x^2)' xlabel 'x' 0:ylabel 'y = -\sqrt{1+x^2}' 0 subplot 2 2 3 '<_':title 'Log-ticks' ranges 0.01 100 0 100:axis 'sqrt(x)' '' '' axis:fplot 'x' xlabel 'x' 1:ylabel 'y = x' 0
You can see that MathGL automatically switch to log-ticks as we define log-axis formula (in difference from v.1.*). Moreover, it switch to log-ticks for any formula if axis range will be large enough (see right bottom plot). Another interesting feature is that you not necessary define usual log-axis (i.e. when coordinates are positive), but you can define “minus-log” axis when coordinate is negative (see left bottom plot).
Next: Colorbars, Previous: Axis and ticks, Up: Advanced usage [Contents][Index]
As I noted in previous subsection, MathGL support curvilinear coordinates. In difference from other plotting programs and libraries, MathGL uses textual formulas for connection of the old (data) and new (output) coordinates. This allows one to plot in arbitrary coordinates. The following code plots the line y=0, z=0 in Cartesian, polar, parabolic and spiral coordinates:
origin -1 1 -1 subplot 2 2 0:title 'Cartesian':rotate 50 60 fplot '2*t-1' '0.5' '0' '2r':axis:grid axis 'y*sin(pi*x)' 'y*cos(pi*x)' '': subplot 2 2 1:title 'Cylindrical':rotate 50 60 fplot '2*t-1' '0.5' '0' '2r':axis:grid axis '2*y*x' 'y*y - x*x' '' subplot 2 2 2:title 'Parabolic':rotate 50 60 fplot '2*t-1' '0.5' '0' '2r':axis:grid axis 'y*sin(pi*x)' 'y*cos(pi*x)' 'x+z' subplot 2 2 3:title 'Spiral':rotate 50 60 fplot '2*t-1' '0.5' '0' '2r':axis:grid
Next: Bounding box, Previous: Curvilinear coordinates, Up: Advanced usage [Contents][Index]
MathGL handle colorbar as special kind of axis. So, most of functions for axis and ticks setup will work for colorbar too. Colorbars can be in log-scale, and generally as arbitrary function scale; common factor of colorbar labels can be separated; and so on.
But of course, there are differences – colorbars usually located out of bounding box. At this, colorbars can be at subplot boundaries (by default), or at bounding box (if symbol ‘I’ is specified). Colorbars can handle sharp colors. And they can be located at arbitrary position too. The sample code, which demonstrate colorbar features is:
call 'prepare2d' new v 9 'x' subplot 2 2 0:title 'Colorbar out of box':box colorbar '<':colorbar '>':colorbar '_':colorbar '^' subplot 2 2 1:title 'Colorbar near box':box colorbar '<I':colorbar '>I':colorbar '_I':colorbar '^I' subplot 2 2 2:title 'manual colors':box:contd v a colorbar v '<':colorbar v '>':colorbar v '_':colorbar v '^' subplot 2 2 3:title '':text -0.5 1.55 'Color positions' ':C' -2 colorbar 'bwr>' 0.25 0:text -0.9 1.2 'Default' colorbar 'b{w,0.3}r>' 0.5 0:text -0.1 1.2 'Manual' crange 0.01 1e3 colorbar '>' 0.75 0:text 0.65 1.2 'Normal scale' colorbar '>':text 1.35 1.2 'Log scale'
Next: Ternary axis, Previous: Colorbars, Up: Advanced usage [Contents][Index]
Box around the plot is rather useful thing because it allows one to: see the plot boundaries, and better estimate points position since box contain another set of ticks. MathGL provide special function for drawing such box – box function. By default, it draw black or white box with ticks (color depend on transparency type, see Types of transparency). However, you can change the color of box, or add drawing of rectangles at rear faces of box. Also you can disable ticks drawing, but I don’t know why anybody will want it. The sample code, which demonstrate box features is:
subplot 2 2 0:title 'Box (default)':rotate 50 60:box subplot 2 2 1:title 'colored':rotate 50 60:box 'r' subplot 2 2 2:title 'with faces':rotate 50 60:box '@' subplot 2 2 3:title 'both':rotate 50 60:box '@cm'
Next: Text features, Previous: Bounding box, Up: Advanced usage [Contents][Index]
There are another unusual axis types which are supported by MathGL. These are ternary and quaternary axis. Ternary axis is special axis of 3 coordinates a, b, c which satisfy relation a+b+c=1. Correspondingly, quaternary axis is special axis of 4 coordinates a, b, c, d which satisfy relation a+b+c+d=1.
Generally speaking, only 2 of coordinates (3 for quaternary) are independent. So, MathGL just introduce some special transformation formulas which treat a as ‘x’, b as ‘y’ (and c as ‘z’ for quaternary). As result, all plotting functions (curves, surfaces, contours and so on) work as usual, but in new axis. You should use ternary function for switching to ternary/quaternary coordinates. The sample code is:
ranges 0 1 0 1 0 1 new x 50 '0.25*(1+cos(2*pi*x))' new y 50 '0.25*(1+sin(2*pi*x))' new z 50 'x' new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)' new rx 10 'rnd':copy ry (1-rx)*rnd light on subplot 2 2 0:title 'Ordinary axis 3D':rotate 50 60 box:axis:grid plot x y z 'r2':surf a '#' xlabel 'B':ylabel 'C':zlabel 'Z' subplot 2 2 1:title 'Ternary axis (x+y+t=1)':ternary 1 box:axis:grid 'xyz' 'B;' plot x y 'r2':plot rx ry 'q^ ':cont a:line 0.5 0 0 0.75 'g2' xlabel 'B':ylabel 'C':tlabel 'A' subplot 2 2 2:title 'Quaternary axis 3D':rotate 50 60:ternary 2 box:axis:grid 'xyz' 'B;' plot x y z 'r2':surf a '#' xlabel 'B':ylabel 'C':tlabel 'A':zlabel 'D' subplot 2 2 3:title 'Ternary axis 3D':rotate 50 60:ternary 1 box:axis:grid 'xyz' 'B;' plot x y z 'r2':surf a '#' xlabel 'B':ylabel 'C':tlabel 'A':zlabel 'Z'
Next: Legend sample, Previous: Ternary axis, Up: Advanced usage [Contents][Index]
MathGL prints text by vector font. There are functions for manual specifying of text position (like Puts
) and for its automatic selection (like Label
, Legend
and so on). MathGL prints text always in specified position even if it lies outside the bounding box. The default size of font is specified by functions SetFontSize* (see Font settings). However, the actual size of output string depends on subplot size (depends on functions SubPlot
, InPlot
). The switching of the font style (italic, bold, wire and so on) can be done for the whole string (by function parameter) or inside the string. By default MathGL parses TeX-like commands for symbols and indexes (see Font styles).
Text can be printed as usual one (from left to right), along some direction (rotated text), or along a curve. Text can be printed on several lines, divided by new line symbol ‘\n’.
Example of MathGL font drawing is:
call 'prepare1d' subplot 2 2 0 '' text 0 1 'Text can be in ASCII and in Unicode' text 0 0.6 'It can be \wire{wire}, \big{big} or #r{colored}' text 0 0.2 'One can change style in string: \b{bold}, \i{italic, \b{both}}' text 0 -0.2 'Easy to \a{overline} or \u{underline}' text 0 -0.6 'Easy to change indexes ^{up} _{down} @{center}' text 0 -1 'It parse TeX: \int \alpha \cdot \ \sqrt3{sin(\pi x)^2 + \gamma_{i_k}} dx' subplot 2 2 1 '' text 0 0.5 '\sqrt{\frac{\alpha^{\gamma^2}+\overset 1{\big\infty}}{\sqrt3{2+b}}}' '@' -2 text 0 -0.5 'Text can be printed\n{}on several lines' subplot 2 2 2 '':box:plot y(:,0) text y 'This is very very long string drawn along a curve' 'k' text y 'Another string drawn under a curve' 'Tr' subplot 2 2 3 '':line -1 -1 1 -1 'rA':text 0 -1 1 -1 'Horizontal' line -1 -1 1 1 'rA':text 0 0 1 1 'At angle' '@' line -1 -1 -1 1 'rA':text -1 0 -1 1 'Vertical'
You can change font faces by loading font files by function loadfont. Note, that this is long-run procedure. Font faces can be downloaded from MathGL website or from here. The sample code is:
define d 0.25 loadfont 'STIX':text 0 1.1 'default font (STIX)' loadfont 'adventor':text 0 1.1-d 'adventor font' loadfont 'bonum':text 0 1.1-2*d 'bonum font' loadfont 'chorus':text 0 1.1-3*d 'chorus font' loadfont 'cursor':text 0 1.1-4*d 'cursor font' loadfont 'heros':text 0 1.1-5*d 'heros font' loadfont 'heroscn':text 0 1.1-6*d 'heroscn font' loadfont 'pagella':text 0 1.1-7*d 'pagella font' loadfont 'schola':text 0 1.1-8*d 'schola font' loadfont 'termes':text 0 1.1-9*d 'termes font'
Next: Cutting sample, Previous: Text features, Up: Advanced usage [Contents][Index]
Legend is one of standard ways to show plot annotations. Basically you need to connect the plot style (line style, marker and color) with some text. In MathGL, you can do it by 2 methods: manually using addlegend function; or use ‘legend’ option (see Command options), which will use last plot style. In both cases, legend entries will be added into internal accumulator, which later used for legend drawing itself. clearlegend function allow you to remove all saved legend entries.
There are 2 features. If plot style is empty then text will be printed without indent. If you want to plot the text with indent but without plot sample then you need to use space ‘ ’ as plot style. Such style ‘ ’ will draw a plot sample (line with marker(s)) which is invisible line (i.e. nothing) and print the text with indent as usual one.
Command legend draw legend on the plot. The position of the legend can be selected automatic or manually. You can change the size and style of text labels, as well as setup the plot sample. The sample code demonstrating legend features is:
addlegend 'sin(\pi {x^2})' 'b' addlegend 'sin(\pi x)' 'g*' addlegend 'sin(\pi \sqrt{x})' 'rd' addlegend 'jsut text' ' ' addlegend 'no indent for this' '' subplot 2 2 0 '':title 'Legend (default)':box legend text 0.75 0.65 'Absolute position' 'A' legend 3 'A#' subplot 2 2 2 '':title 'coloring':box legend 0 'r#':legend 1 'Wb#':legend 2 'ygr#' subplot 2 2 3 '':title 'manual position':box legend 0.5 1:text 0.5 0.55 'at x=0.5, y=1' 'a' legend 1 '#-':text 0.75 0.25 'Horizontal legend' 'a'
Previous: Legend sample, Up: Advanced usage [Contents][Index]
The last common thing which I want to show in this section is how one can cut off points from plot. There are 4 mechanism for that.
SetCut
function. As result all points out of bounding box will be omitted.
SetCutBox
function. All points inside this box will be omitted.
SetCutOff
function. All points for which the value of formula is nonzero will be omitted. Note, that this is the slowest variant.
Below I place the code which demonstrate last 3 possibilities:
call 'prepare2d' call 'prepare3d' subplot 2 2 0:title 'Cut on (default)':rotate 50 60 light on:box:surf a; zrange -1 0.5 subplot 2 2 1:title 'Cut off':rotate 50 60 box:surf a; zrange -1 0.5; cut off subplot 2 2 2:title 'Cut in box':rotate 50 60:box:alpha on cut 0 -1 -1 1 0 1.1:surf3 c cut 0 0 0 0 0 0 # restore back subplot 2 2 3:title 'Cut by formula':rotate 50 60:box cut '(z>(x+0.5*y-1)^2-1) & (z>(x-0.5*y-1)^2-1)':surf3 c
Next: Data plotting, Previous: Advanced usage, Up: Examples [Contents][Index]
Class mglData
contains all functions for the data handling in MathGL (see Data processing). There are several matters why I use class mglData
but not a single array: it does not depend on type of data (mreal or double), sizes of data arrays are kept with data, memory working is simpler and safer.
• Array creation: | ||
• Change data: |
Next: Change data, Up: Data handling [Contents][Index]
One can put numbers into the data instance by several ways. Let us do it for square function:
list
command
list a 0 0.04 0.16 0.36 0.64 1
copy a [0,0.04,0.16,0.36,0.64,1]
modify
function
new a 6 modify a 'x^2'
new a 6 fill a 0 1 modify a 'u^2'
new a 6 fill a '(x+1)^2/4'
or use single line
new a 6 '(x+1)^2/4'
new s 6 '(x+1)^2/4' save s 'sqr.dat' # create file first read a 'sqr.dat' # load it
new s 6 '(x+1)^2/4' save s 'sqr.dat' # create file first read a 'sqr.dat' 5 # load it
Creation of 2d- and 3d-arrays is mostly the same. One can use direct data filling by list
command
list a 11 12 13 | 21 22 23 | 31 32 33
or by inline arrays
copy a [[11,12,13],[21,22,23],[31,32,33]]
Also data can be filled by formula
new z 30 40 'sin(pi*x)*cos(pi*y)'
or loaded from a file.
Previous: Array creation, Up: Data handling [Contents][Index]
MathGL has functions for data processing: differentiating, integrating, smoothing and so on (for more detail, see Data processing). Let us consider some examples. The simplest ones are integration and differentiation. The direction in which operation will be performed is specified by textual string, which may contain symbols ‘x’, ‘y’ or ‘z’. For example, the call of diff 'x'
will differentiate data along ‘x’ direction; the call of integrate 'xy'
perform the double integration of data along ‘x’ and ‘y’ directions; the call of diff2 'xyz'
will apply 3d Laplace operator to data and so on. Example of this operations on 2d array a=x*y is presented in code:
ranges 0 1 0 1 0 1:new a 30 40 'x*y' subplot 2 2 0:title 'a(x,y)':rotate 60 40 surf a:box subplot 2 2 1:title 'da/dx':rotate 60 40 diff a 'x':surf a:box subplot 2 2 2:title '\int da/dx dxdy':rotate 60 40 integrate a 'xy':surf a:box subplot 2 2 3:title '\int {d^2}a/dxdy dx':rotate 60 40 diff2 a 'y':surf a:box
Data smoothing (command smooth) is more interesting and important. This function has single argument which define type of smoothing and its direction. Now 3 methods are supported: ‘3’ – linear averaging by 3 points, ‘5’ – linear averaging by 5 points, and default one – quadratic averaging by 5 points.
MathGL also have some amazing functions which is not so important for data processing as useful for data plotting. There are functions for finding envelope (useful for plotting rapidly oscillating data), for data sewing (useful to removing jumps on the phase), for data resizing (interpolation). Let me demonstrate it:
subplot 2 2 0 '':title 'Envelop sample' new d1 1000 'exp(-8*x^2)*sin(10*pi*x)' axis:plot d1 'b' envelop d1 'x' plot d1 'r' subplot 2 2 1 '':title 'Smooth sample':ranges 0 1 0 1 new y0 30 '0.4*sin(pi*x) + 0.3*cos(1.5*pi*x) - 0.4*sin(2*pi*x)+0.5*rnd' copy y1 y0:smooth y1 'x3':plot y1 'r';legend '"3" style' copy y2 y0:smooth y2 'x5':plot y2 'g';legend '"5" style' copy y3 y0:smooth y3 'x':plot y3 'b';legend 'default' plot y0 '{m7}:s';legend 'none':legend:box subplot 2 2 2:title 'Sew sample':rotate 50 60:light on:alpha on new d2 100 100 'mod((y^2-(1-x)^2)/2,0.1)' box:surf d2 'b' sew d2 'xy' 0.1 surf d2 'r' subplot 2 2 3:title 'Resize sample (interpolation)' new x0 10 'rnd':new v0 10 'rnd' resize x1 x0 100:resize v1 v0 100 plot x0 v0 'b+ ':plot x1 v1 'r-':label x0 v0 '%n'
Finally one can create new data arrays on base of the existing one: extract slice, row or column of data (subdata), summarize along a direction(s) (sum), find distribution of data elements (hist) and so on.
Another interesting feature of MathGL is interpolation and root-finding. There are several functions for linear and cubic spline interpolation (see Interpolation). Also there is a function evaluate which do interpolation of data array for values of each data element of index data. It look as indirect access to the data elements.
This function have inverse function solve which find array of indexes at which data array is equal to given value (i.e. work as root finding). But solve function have the issue – usually multidimensional data (2d and 3d ones) have an infinite number of indexes which give some value. This is contour lines for 2d data, or isosurface(s) for 3d data. So, solve function will return index only in given direction, assuming that other index(es) are the same as equidistant index(es) of original data. Let me demonstrate this on the following sample.
zrange 0 1 new x 20 30 '(x+2)/3*cos(pi*y)' new y 20 30 '(x+2)/3*sin(pi*y)' new z 20 30 'exp(-6*x^2-2*sin(pi*y)^2)' subplot 2 1 0:title 'Cartesian space':rotate 30 -40 axis 'xyzU':box xlabel 'x':ylabel 'y'origin 1 1:grid 'xy' mesh x y z # section along 'x' direction solve u x 0.5 'x' var v u.nx 0 1 evaluate yy y u v evaluate xx x u v evaluate zz z u v plot xx yy zz 'k2o' # 1st section along 'y' direction solve u1 x -0.5 'y' var v1 u1.nx 0 1 evaluate yy y v1 u1 evaluate xx x v1 u1 evaluate zz z v1 u1 plot xx yy zz 'b2^' # 2nd section along 'y' direction solve u2 x -0.5 'y' u1 evaluate yy y v1 u2 evaluate xx x v1 u2 evaluate zz z v1 u2 plot xx yy zz 'r2v' subplot 2 1 1:title 'Accompanied space' ranges 0 1 0 1:origin 0 0 axis:box:xlabel 'i':ylabel 'j':grid2 z 'h' plot u v 'k2o':line 0.4 0.5 0.8 0.5 'kA' plot v1 u1 'b2^':line 0.5 0.15 0.5 0.3 'bA' plot v1 u2 'r2v':line 0.5 0.7 0.5 0.85 'rA'
Next: 1D samples, Previous: Data handling, Up: Examples [Contents][Index]
Let me now show how to plot the data. Next section will give much more examples for all plotting functions. Here I just show some basics. MathGL generally has 2 types of plotting functions. Simple variant requires a single data array for plotting, other data (coordinates) are considered uniformly distributed in axis range. Second variant requires data arrays for all coordinates. It allows one to plot rather complex multivalent curves and surfaces (in case of parametric dependencies). Usually each function have one textual argument for plot style and accept options (see Command options).
Note, that the call of drawing function adds something to picture but does not clear the previous plots (as it does in Matlab). Another difference from Matlab is that all setup (like transparency, lightning, axis borders and so on) must be specified before plotting functions.
Let start for plots for 1D data. Term “1D data” means that data depend on single index (parameter) like curve in parametric form {x(i),y(i),z(i)}, i=1...n. The textual argument allow you specify styles of line and marks (see Line styles). If this parameter is empty ''
then solid line with color from palette is used (see Palette and colors).
Below I shall show the features of 1D plotting on base of plot function. Let us start from sinus plot:
new y0 50 'sin(pi*x)' subplot 2 2 0 plot y0:box
Style of line is not specified in plot function. So MathGL uses the solid line with first color of palette (this is blue). Next subplot shows array y1 with 2 rows:
subplot 2 2 1 new y1 50 2 fill y1 'cos(pi*(x+y/4))*2/(y+3)' plot y1:box
As previously I did not specify the style of lines. As a result, MathGL again uses solid line with next colors in palette (there are green and red). Now let us plot a circle on the same subplot. The circle is parametric curve x=cos(\pi t), y=sin(\pi t). I will set the color of the circle (dark yellow, ‘Y’) and put marks ‘+’ at point position:
new x 50 'cos(pi*x)' plot x y0 'Y+'
Note that solid line is used because I did not specify the type of line. The same picture can be achieved by plot and subdata functions. Let us draw ellipse by orange dash line:
plot y1(:,0) y1(:,1) 'q|'
Drawing in 3D space is mostly the same. Let us draw spiral with default line style. Now its color is 4-th color from palette (this is cyan):
subplot 2 2 2:rotate 60 40 new z 50 'x' plot x y0 z:box
Functions plot and subdata make 3D curve plot but for single array. Use it to put circle marks on the previous plot:
new y2 10 3 'cos(pi*(x+y/2))' modify y2 '2*x-1' 2 plot y2(:,0) y2(:,1) y2(:,2) 'bo '
Note that line style is empty ‘ ’ here. Usage of other 1D plotting functions looks similar:
subplot 2 2 3:rotate 60 40 bars x y0 z 'r':box
Surfaces surf and other 2D plots (see 2D plotting) are drown the same simpler as 1D one. The difference is that the string parameter specifies not the line style but the color scheme of the plot (see Color scheme). Here I draw attention on 4 most interesting color schemes. There is gray scheme where color is changed from black to white (string ‘kw’) or from white to black (string ‘wk’). Another scheme is useful for accentuation of negative (by blue color) and positive (by red color) regions on plot (string ‘"BbwrR"’). Last one is the popular “jet” scheme (string ‘"BbcyrR"’).
Now I shall show the example of a surface drawing. At first let us switch lightning on
light on
and draw the surface, considering coordinates x,y to be uniformly distributed in axis range
new a0 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' subplot 2 2 0:rotate 60 40 surf a0:box
Color scheme was not specified. So previous color scheme is used. In this case it is default color scheme (“jet”) for the first plot. Next example is a sphere. The sphere is parametrically specified surface:
new x 50 40 '0.8*sin(pi*x)*cos(pi*y/2)' new y 50 40 '0.8*cos(pi*x)*cos(pi*y/2)' new z 50 40 '0.8*sin(pi*y/2)' subplot 2 2 1:rotate 60 40 surf x y z 'BbwrR':box
I set color scheme to "BbwrR"
that corresponds to red top and blue bottom of the sphere.
Surfaces will be plotted for each of slice of the data if nz>1. Next example draws surfaces for data arrays with nz=3:
new a1 50 40 3 modify a1 '0.6*sin(2*pi*x)*sin(3*pi*y)+0.4*cos(3*pi*(x*y))' modify a1 '0.6*cos(2*pi*x)*cos(3*pi*y)+0.4*sin(3*pi*(x*y))' 1 modify a1 '0.6*cos(2*pi*x)*cos(3*pi*y)+0.4*cos(3*pi*(x*y))' 2 subplot 2 2 2:rotate 60 40 alpha on surf a1:box
Note, that it may entail a confusion. However, if one will use density plot then the picture will look better:
subplot 2 2 3:rotate 60 40 dens a1:box
Drawing of other 2D plots is analogous. The only peculiarity is the usage of flag ‘#’. By default this flag switches on the drawing of a grid on plot (grid or mesh for plots in plain or in volume). However, for isosurfaces (including surfaces of rotation axial) this flag switches the face drawing off and figure becomes wired.
Next: 2D samples, Previous: Data plotting, Up: Examples [Contents][Index]
This section is devoted to visualization of 1D data arrays. 1D means the data which depend on single index (parameter) like curve in parametric form {x(i),y(i),z(i)}, i=1...n. Most of samples will use the same data for plotting. So, I put its initialization in separate function
func 'prepare1d' new y 50 3 modify y '0.7*sin(2*pi*x)+0.5*cos(3*pi*x)+0.2*sin(pi*x)' modify y 'sin(2*pi*x)' 1 modify y 'cos(2*pi*x)' 2 new x1 50 'x' new x2 50 '0.05-0.03*cos(pi*x)' new y1 50 '0.5-0.3*cos(pi*x)' new y2 50 '-0.3*sin(pi*x)' return
Basically, you can put this text after the script. Note, that you need to terminate main script by stop command before defining a function.
• Plot sample: | ||
• Radar sample: | ||
• Step sample: | ||
• Tens sample: | ||
• Area sample: | ||
• Region sample: | ||
• Stem sample: | ||
• Bars sample: | ||
• Barh sample: | ||
• Cones sample: | ||
• Chart sample: | ||
• BoxPlot sample: | ||
• Candle sample: | ||
• OHLC sample: | ||
• Error sample: | ||
• Mark sample: | ||
• TextMark sample: | ||
• Label sample: | ||
• Table sample: | ||
• Tube sample: | ||
• Tape sample: | ||
• Torus sample: | ||
• Lamerey sample: | ||
• Bifurcation sample: | ||
• Pmap sample: |
Next: Radar sample, Up: 1D samples [Contents][Index]
Command plot is most standard way to visualize 1D data array. By default, Plot
use colors from palette. However, you can specify manual color/palette, and even set to use new color for each points by using ‘!’ style. Another feature is ‘ ’ style which draw only markers without line between points. The sample code is:
call 'prepare1d' subplot 2 2 0 '':title 'Plot plot (default)':box plot y subplot 2 2 2 '':title ''!' style; 'rgb' palette':box plot y 'o!rgb' subplot 2 2 3 '':title 'just markers':box plot y ' +' new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 1:title '3d variant':rotate 50 60:box plot xc yc z 'rs'
Next: Step sample, Previous: Plot sample, Up: 1D samples [Contents][Index]
Command radar plot is variant of Plot
one, which make plot in polar coordinates and draw radial rays in point directions. If you just need a plot in polar coordinates then I recommend to use Curvilinear coordinates or Plot
in parabolic form with x=r*cos(fi); y=r*sin(fi);
. The sample code is:
new yr 10 3 '0.4*sin(pi*(x+1.5+y/2)+0.1*rnd)' subplot 1 1 0 '':title 'Radar plot (with grid, "\#")' radar yr '#'
Next: Tens sample, Previous: Radar sample, Up: 1D samples [Contents][Index]
Command step plot data as stairs. It have the same options as Plot
. The sample code is:
call 'prepare1d' origin 0 0 0:subplot 2 2 0 '':title 'Step plot (default)':box step y new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 1:title '3d variant':rotate 50 60:box step xc yc z 'r' subplot 2 2 2 '':title '"!" style':box step y 's!rgb'
Next: Area sample, Previous: Step sample, Up: 1D samples [Contents][Index]
Command tens is variant of plot with smooth coloring along the curves. At this, color is determined as for surfaces (see Color scheme). The sample code is:
call 'prepare1d' subplot 2 2 0 '':title 'Tens plot (default)':box tens y(:,0) y(:,1) subplot 2 2 2 '':title ' style':box tens y(:,0) y(:,1) 'o ' new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 1:title '3d variant':rotate 50 60:box tens xc yc z z 's'
Next: Region sample, Previous: Tens sample, Up: 1D samples [Contents][Index]
Command area fill the area between curve and axis plane. It support gradient filling if 2 colors per curve is specified. The sample code is:
call 'prepare1d' origin 0 0 0 subplot 2 2 0 '':title 'Area plot (default)':box area y subplot 2 2 1 '':title '2 colors':box area y 'cbgGyr' subplot 2 2 2 '':title '"!" style':box area y '!' new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 3:title '3d variant':rotate 50 60:box area xc yc z 'r':area xc -yc z 'b#'
Next: Stem sample, Previous: Area sample, Up: 1D samples [Contents][Index]
Command region fill the area between 2 curves. It support gradient filling if 2 colors per curve is specified. Also it can fill only the region y1<y<y2 if style ‘i’ is used. The sample code is:
call 'prepare1d' copy y1 y(:,1):copy y2 y(:,2) subplot 2 2 0 '':title 'Region plot (default)':box region y1 y2:plot y1 'k2':plot y2 'k2' subplot 2 2 1 '':title '2 colors':box region y1 y2 'yr':plot y1 'k2':plot y2 'k2' subplot 2 2 2 '':title '"i" style':box region y1 y2 'ir':plot y1 'k2':plot y2 'k2' subplot 2 2 3 '^_':title '3d variant':rotate 40 60:box new x1 100 'sin(pi*x)':new y1 100 'cos(pi*x)':new z 100 'x' new x2 100 'sin(pi*x+pi/3)':new y2 100 'cos(pi*x+pi/3)' plot x1 y1 z 'r2':plot x2 y2 z 'b2' region x1 y1 z x2 y2 z 'cmy!'
Next: Bars sample, Previous: Region sample, Up: 1D samples [Contents][Index]
Command stem draw vertical bars. It is most attractive if markers are drawn too. The sample code is:
call 'prepare1d' origin 0 0 0:subplot 2 2 0 '':title 'Stem plot (default)':box stem y new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 1:title '3d variant':rotate 50 60:box stem xc yc z 'rx' subplot 2 2 2 '':title '"!" style':box stem y 'o!rgb'
Next: Barh sample, Previous: Stem sample, Up: 1D samples [Contents][Index]
Command bars draw vertical bars. It have a lot of options: bar-above-bar (‘a’ style), fall like (‘f’ style), 2 colors for positive and negative values, wired bars (‘#’ style), 3D variant. The sample code is:
new ys 10 3 '0.8*sin(pi*(x+y/4+1.25))+0.2*rnd':origin 0 0 0 subplot 3 2 0 '':title 'Bars plot (default)':box bars ys subplot 3 2 1 '':title '2 colors':box bars ys 'cbgGyr' subplot 3 2 4 '':title '"\#" style':box bars ys '#' new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 3 2 5:title '3d variant':rotate 50 60:box bars xc yc z 'r' subplot 3 2 2 '':title '"a" style':ranges -1 1 -3 3:box bars ys 'a' subplot 3 2 3 '':title '"f" style':box bars ys 'f'
Next: Cones sample, Previous: Bars sample, Up: 1D samples [Contents][Index]
Command barh is the similar to Bars
but draw horizontal bars. The sample code is:
new ys 10 3 '0.8*sin(pi*(x+y/4+1.25))+0.2*rnd':origin 0 0 0 subplot 2 2 0 '':title 'Barh plot (default)':box barh ys subplot 2 2 1 '':title '2 colors':box barh ys 'cbgGyr' ranges -3 3 -1 1:subplot 2 2 2 '':title '"a" style':box:barh ys 'a' subplot 2 2 3 '': title '"f" style':box barh ys 'f'
Next: Chart sample, Previous: Bars sample, Up: 1D samples [Contents][Index]
Command cones is similar to Bars
but draw cones. The sample code is:
new ys 10 3 '0.8*sin(pi*(x+y/4+1.25))+0.2*rnd' origin 0 0 0:light on subplot 3 2 0:title 'Cones plot':rotate 50 60:box cones ys subplot 3 2 1:title '2 colors':rotate 50 60:box cones ys 'cbgGyr' subplot 3 2 2:title '"\#" style':rotate 50 60:box cones ys '#' subplot 3 2 3:title '"a" style':rotate 50 60:zrange -2 2:box cones ys 'a' subplot 3 2 4:title '"t" style':rotate 50 60:box cones ys 't' subplot 3 2 5:title '"4" style':rotate 50 60:box cones ys '4'
Next: BoxPlot sample, Previous: Cones sample, Up: 1D samples [Contents][Index]
Command chart draw colored boxes with width proportional to data values. Use ‘ ’ for empty box. Plot looks most attractive in polar coordinates – well known pie chart. The sample code is:
new ch 7 2 'rnd+0.1':light on subplot 2 2 0:title 'Chart plot (default)':rotate 50 60:box chart ch subplot 2 2 1:title '"\#" style':rotate 50 60:box chart ch '#' subplot 2 2 2:title 'Pie chart; " " color':rotate 50 60: axis '(y+1)/2*cos(pi*x)' '(y+1)/2*sin(pi*x)' '':box chart ch 'bgr cmy#' subplot 2 2 3:title 'Ring chart; " " color':rotate 50 60: axis '(y+2)/3*cos(pi*x)' '(y+2)/3*sin(pi*x)' '':box chart ch 'bgr cmy#'
Next: Candle sample, Previous: Chart sample, Up: 1D samples [Contents][Index]
Command boxplot draw box-and-whisker diagram. The sample code is:
new a 10 7 '(2*rnd-1)^3/2' subplot 1 1 0 '':title 'Boxplot plot':box boxplot a
Next: OHLC sample, Previous: BoxPlot sample, Up: 1D samples [Contents][Index]
Command candle draw candlestick chart. This is a combination of a line-chart and a bar-chart, in that each bar represents the range of price movement over a given time interval. The sample code is:
new y 30 'sin(pi*x/2)^2':copy y1 y/2:copy y2 (y+1)/2 subplot 1 1 0 '':title 'Candle plot (default)':yrange 0 1:box candle y y1 y2
Next: Error sample, Previous: Candle sample, Up: 1D samples [Contents][Index]
Command ohlc draw Open-High-Low-Close diagram. This diagram show vertical line for between maximal(high) and minimal(low) values, as well as horizontal lines before/after vertical line for initial(open)/final(close) values of some process. The sample code is:
new o 10 '0.5*sin(pi*x)' new c 10 '0.5*sin(pi*(x+2/9))' new l 10 '0.3*rnd-0.8' new h 10 '0.3*rnd+0.5' subplot 1 1 0 '':title 'OHLC plot':box ohlc o h l c
Next: Mark sample, Previous: OHLC sample, Up: 1D samples [Contents][Index]
Command error draw error boxes around the points. You can draw default boxes or semi-transparent symbol (like marker, see Line styles). Also you can set individual color for each box. The sample code is:
call 'prepare1d' new y 50 '0.7*sin(pi*x-pi) + 0.5*cos(3*pi*(x+1)/2) + 0.2*sin(pi*(x+1)/2)' new x0 10 'x + 0.1*rnd-0.05':new ex 10 '0.1':new ey 10 '0.2' new y0 10 '0.7*sin(pi*x-pi) + 0.5*cos(3*pi*(x+1)/2) + 0.2*sin(pi*(x+1)/2) + 0.2*rnd-0.1' subplot 2 2 0 '':title 'Error plot (default)':box:plot y error x0 y0 ex ey 'k' subplot 2 2 1 '':title '"!" style; no e_x':box:plot y error x0 y0 ey 'o!rgb' subplot 2 2 2 '':title '"\@" style':box:plot y error x0 y0 ex ey '@'; alpha 0.5 subplot 2 2 3:title '3d variant':rotate 50 60:axis for $1 0 9 errbox 2*rnd-1 2*rnd-1 2*rnd-1 0.2 0.2 0.2 'bo' next
Additionally, you can use solid large "marks" instead of error boxes by selecting proper style.
new x0 10 'rnd':new ex 10 '0.1' new y0 10 'rnd':new ey 10 '0.1' ranges 0 1 0 1 subplot 4 3 0 '':box:error x0 y0 ex ey '#+@' subplot 4 3 1 '':box:error x0 y0 ex ey '#x@' subplot 4 3 2 '':box:error x0 y0 ex ey '#s@'; alpha 0.5 subplot 4 3 3 '':box:error x0 y0 ex ey 's@' subplot 4 3 4 '':box:error x0 y0 ex ey 'd@' subplot 4 3 5 '':box:error x0 y0 ex ey '#d@'; alpha 0.5 subplot 4 3 6 '':box:error x0 y0 ex ey '+@' subplot 4 3 7 '':box:error x0 y0 ex ey 'x@' subplot 4 3 8 '':box:error x0 y0 ex ey 'o@' subplot 4 3 9 '':box:error x0 y0 ex ey '#o@'; alpha 0.5 subplot 4 3 10 '':box:error x0 y0 ex ey '#.@' subplot 4 3 11 '':box:error x0 y0 ex ey; alpha 0.5
Next: TextMark sample, Previous: Error sample, Up: 1D samples [Contents][Index]
Command mark draw markers at points. It is mostly the same as Plot
but marker size can be variable. The sample code is:
call 'prepare1d' subplot 1 1 0 '':title 'Mark plot (default)':box mark y y1 's'
Next: Label sample, Previous: Mark sample, Up: 1D samples [Contents][Index]
Command textmark like Mark
but draw text instead of markers. The sample code is:
call 'prepare1d' subplot 1 1 0 '':title 'TextMark plot (default)':box textmark y y1 '\gamma' 'r'
Next: Table sample, Previous: TextMark sample, Up: 1D samples [Contents][Index]
Command label print text at data points. The string may contain ‘%x’, ‘%y’, ‘%z’ for x-, y-, z-coordinates of points, ‘%n’ for point index. The sample code is:
new ys 10 '0.2*rnd-0.8*sin(pi*x)' subplot 1 1 0 '':title 'Label plot':box plot ys ' *':label ys 'y=%y'
Next: Tube sample, Previous: Label sample, Up: 1D samples [Contents][Index]
Command table draw table with data values. The sample code is:
new ys 10 3 '0.8*sin(pi*(x+y/4+1.25))+0.2*rnd' subplot 2 2 0:title 'Table sample':box table ys 'y_1\n{}y_2\n{}y_3' subplot 2 2 1:title 'no borders, colored' table ys 'y_1\n{}y_2\n{}y_3' 'r|' subplot 2 2 2:title 'no font decrease' table ys 'y_1\n{}y_2\n{}y_3' '#' subplot 2 2 3:title 'manual width and position':box table 0.5 0.95 ys 'y_1\n{}y_2\n{}y_3' '#';value 0.7
Next: Tape sample, Previous: Table sample, Up: 1D samples [Contents][Index]
Command tube draw tube with variable radius. The sample code is:
light on:call 'prepare1d' new yc 50 'sin(pi*x)':new xc 50 'cos(pi*x)':new z 50 'x':divto y1 20 subplot 2 2 0 '':title 'Tube plot (default)':box tube y 0.05 subplot 2 2 1 '':title 'variable radius':box tube y y1 subplot 2 2 2 '':title '"\#" style':box tube y 0.05 '#' subplot 2 2 3:title '3d variant':rotate 50 60:box tube xc yc z y2 'r'
Next: Torus sample, Previous: Tube sample, Up: 1D samples [Contents][Index]
Command tape draw tapes which rotate around the curve as normal and binormal. The sample code is:
call 'prepare1d' new yc 50 'sin(pi*x)':new xc 50 'cos(pi*x)':new z 50 'x' subplot 2 2 0 '':title 'Tape plot (default)':box tape y:plot y 'k' subplot 2 2 1:title '3d variant, 2 colors':rotate 50 60:light on:box plot xc yc z 'k':tape xc yc z 'rg' subplot 2 2 2:title '3d variant, x only':rotate 50 60:box plot xc yc z 'k':tape xc yc z 'xr':tape xc yc z 'xr#' subplot 2 2 3:title '3d variant, z only':rotate 50 60:box plot xc yc z 'k':tape xc yc z 'zg':tape xc yc z 'zg#'
Next: Lamerey sample, Previous: Tape sample, Up: 1D samples [Contents][Index]
Command torus draw surface of the curve rotation. The sample code is:
call 'prepare1d' subplot 2 2 0:title 'Torus plot (default)':light on:rotate 50 60:box torus y1 y2 subplot 2 2 1:title '"x" style':light on:rotate 50 60:box torus y1 y2 'x' subplot 2 2 2:title '"z" style':light on:rotate 50 60:box torus y1 y2 'z' subplot 2 2 3:title '"\#" style':light on:rotate 50 60:box torus y1 y2 '#'
Next: Bifurcation sample, Previous: Torus sample, Up: 1D samples [Contents][Index]
Function lamerey draw Lamerey diagram. The sample code is:
subplot 1 1 0 '<_':title 'Lamerey sample' axis:xlabel '\i x':ylabel '\bar{\i x} = 2 \i{x}' fplot 'x' 'k=' fplot '2*x' 'b' lamerey 0.00097 '2*x' 'rv~';size 2 lamerey -0.00097 '2*x' 'rv~';size 2
Next: Pmap sample, Previous: Lamerey sample, Up: 1D samples [Contents][Index]
Function bifurcation draw Bifurcation diagram for logistic map. The sample code is:
subplot 1 1 0 '<_':title 'Bifurcation sample' ranges 0 4 0 1:axis bifurcation 0.005 'x*y*(1-y)' 'r'
Previous: Bifurcation sample, Up: 1D samples [Contents][Index]
Function pmap draw Poincare map – show intersections of the curve and the surface. The sample code is:
subplot 1 1 0 '<_^':title 'Poincare map sample' ode r 'cos(y)+sin(z);cos(z)+sin(x);cos(x)+sin(y)' 'xyz' [0.1,0,0] 0.1 100 rotate 40 60:copy x r(0):copy y r(1):copy z r(2) ranges x y z axis:plot x y z 'b':fsurf '0' xlabel '\i x' 0:ylabel '\i y' 0:zlabel '\i z' pmap x y z z 'b#o'
Next: 3D samples, Previous: 1D samples, Up: Examples [Contents][Index]
This section is devoted to visualization of 2D data arrays. 2D means the data which depend on 2 indexes (parameters) like matrix z(i,j)=z(x(i),y(j)), i=1...n, j=1...m or in parametric form {x(i,j),y(i,j),z(i,j)}. Most of samples will use the same data for plotting. So, I put its initialization in separate function
func 'prepare2d' new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' return
Basically, you can put this text after the script. Note, that you need to terminate main script by stop command before defining a function.
• Surf sample: | ||
• SurfC sample: | ||
• SurfA sample: | ||
• SurfCA sample: | ||
• Mesh sample: | ||
• Fall sample: | ||
• Belt sample: | ||
• Boxs sample: | ||
• Tile sample: | ||
• TileS sample: | ||
• Dens sample: | ||
• Cont sample: | ||
• ContF sample: | ||
• ContD sample: | ||
• ContV sample: | ||
• Axial sample: | ||
• Grad sample: |
Next: SurfC sample, Up: 2D samples [Contents][Index]
Command surf is most standard way to visualize 2D data array. Surf
use color scheme for coloring (see Color scheme). You can use ‘#’ style for drawing black meshes on the surface. The sample code is:
call 'prepare2d' subplot 2 2 0:title 'Surf plot (default)':rotate 50 60:light on:box:surf a subplot 2 2 1:title '"\#" style; meshnum 10':rotate 50 60:box surf a '#'; meshnum 10 subplot 2 2 2:title '"." style':rotate 50 60:box surf a '.' new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)' new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)' new z 50 40 '0.8*cos(pi*(y+1)/2)' subplot 2 2 3:title 'parametric form':rotate 50 60:box surf x y z 'BbwrR'
Next: SurfA sample, Previous: Surf sample, Up: 2D samples [Contents][Index]
Command surfc is similar to surf but its coloring is determined by another data. The sample code is:
call 'prepare2d' title 'SurfC plot':rotate 50 60:light on:box surfc a b
Next: SurfCA sample, Previous: SurfC sample, Up: 2D samples [Contents][Index]
Command surfa is similar to surf but its transparency is determined by another data. The sample code is:
call 'prepare2d' title 'SurfA plot':rotate 50 60:light on:alpha on:box surfa a b
Next: Mesh sample, Previous: SurfA sample, Up: 2D samples [Contents][Index]
Command surfca is similar to surf but its color and transparency is determined by another data. The sample code is:
call 'prepare2d' title 'SurfCA plot':rotate 50 60:light on:alpha on:box surfa a b a
Next: Fall sample, Previous: SurfCA sample, Up: 2D samples [Contents][Index]
Command mesh draw wired surface. You can use meshnum for changing number of lines to be drawn. The sample code is:
call 'prepare2d' title 'Mesh plot':rotate 50 60:box mesh a
Next: Belt sample, Previous: Mesh sample, Up: 2D samples [Contents][Index]
Command fall draw waterfall surface. You can use meshnum for changing number of lines to be drawn. Also you can use ‘x’ style for drawing lines in other direction. The sample code is:
call 'prepare2d' title 'Fall plot':rotate 50 60:box fall a
Next: Boxs sample, Previous: Fall sample, Up: 2D samples [Contents][Index]
Command belt draw surface by belts. You can use ‘x’ style for drawing lines in other direction. The sample code is:
call 'prepare2d' title 'Belt plot':rotate 50 60:box belt a
Next: Tile sample, Previous: Fall sample, Up: 2D samples [Contents][Index]
Command boxs draw surface by boxes. You can use ‘#’ for drawing wire plot. The sample code is:
call 'prepare2d' origin 0 0 0 subplot 2 2 0:title 'Boxs plot (default)':rotate 40 60:light on:box boxs a subplot 2 2 1:title '"\@" style':rotate 50 60:box boxs a '@' subplot 2 2 2:title '"\#" style':rotate 50 60:box boxs a '#' subplot 2 2 3:title 'compare with Tile':rotate 50 60:box tile a
Next: TileS sample, Previous: Boxs sample, Up: 2D samples [Contents][Index]
Command tile draw surface by tiles. The sample code is:
call 'prepare2d' subplot 1 1 0 '':title 'Tiles plot':box tile a
Next: Dens sample, Previous: Tile sample, Up: 2D samples [Contents][Index]
Command tiles is similar to tile but tile sizes is determined by another data. This allows one to simulate transparency of the plot. The sample code is:
call 'prepare2d' subplot 1 1 0 '':title 'Tiles plot':box tiles a b
Next: Cont sample, Previous: TileS sample, Up: 2D samples [Contents][Index]
Command dens draw density plot for surface. The sample code is:
call 'prepare2d' subplot 2 2 0 '':title 'Dens plot (default)':box dens a subplot 2 2 1:title '3d variant':rotate 50 60:box dens a subplot 2 2 2 '':title '"\#" style; meshnum 10':box dens a '#'; meshnum 10 new a1 30 40 3 '0.6*sin(2*pi*x+pi*(z+1)/2)*sin(3*pi*y+pi*z) +\ 0.4*cos(3*pi*(x*y)+pi*(z+1)^2/2)' subplot 2 2 3:title 'several slices':rotate 50 60:box dens a1
Next: ContF sample, Previous: Dens sample, Up: 2D samples [Contents][Index]
Command cont draw contour lines for surface. You can select automatic (default) or manual levels for contours, print contour labels, draw it on the surface (default) or at plane (as Dens
). The sample code is:
call 'prepare2d' list v -0.5 -0.15 0 0.15 0.5 subplot 2 2 0:title 'Cont plot (default)':rotate 50 60:box cont a subplot 2 2 1:title 'manual levels':rotate 50 60:box cont v a subplot 2 2 2:title '"\_" style':rotate 50 60:box cont a '_' subplot 2 2 3 '':title '"t" style':box cont a 't'
Next: ContD sample, Previous: Cont sample, Up: 2D samples [Contents][Index]
Command contf draw filled contours. You can select automatic (default) or manual levels for contours. The sample code is:
call 'prepare2d' list v -0.5 -0.15 0 0.15 0.5 subplot 2 2 0:title 'ContF plot (default)':rotate 50 60:box contf a subplot 2 2 1:title 'manual levels':rotate 50 60:box contf v a subplot 2 2 2:title '"\_" style':rotate 50 60:box contf a '_' new a1 30 40 3 '0.6*sin(2*pi*x+pi*(z+1)/2)*sin(3*pi*y+pi*z) +\ 0.4*cos(3*pi*(x*y)+pi*(z+1)^2/2)' subplot 2 2 3:title 'several slices':rotate 50 60:box contf a1
Next: ContV sample, Previous: ContF sample, Up: 2D samples [Contents][Index]
Command contd is similar to ContF
but with manual contour colors. The sample code is:
call 'prepare2d' list v -0.5 -0.15 0 0.15 0.5 subplot 2 2 0:title 'ContD plot (default)':rotate 50 60:box contd a subplot 2 2 1:title 'manual levels':rotate 50 60:box contd v a subplot 2 2 2:title '"\_" style':rotate 50 60:box contd a '_' new a1 30 40 3 '0.6*sin(2*pi*x+pi*(z+1)/2)*sin(3*pi*y+pi*z) +\ 0.4*cos(3*pi*(x*y)+pi*(z+1)^2/2)' subplot 2 2 3:title 'several slices':rotate 50 60:box contd a1
Next: Axial sample, Previous: ContD sample, Up: 2D samples [Contents][Index]
Command contv draw vertical cylinders (belts) at contour lines. The sample code is:
call 'prepare2d' list v -0.5 -0.15 0 0.15 0.5 subplot 2 2 0:title 'ContV plot (default)':rotate 50 60:box contv a subplot 2 2 1:title 'manual levels':rotate 50 60:box contv v a subplot 2 2 2:title '"\_" style':rotate 50 60:box contv a '_' subplot 2 2 3:title 'ContV and ContF':rotate 50 60:light on:box contv a:contf a:cont a 'k'
Next: Grad sample, Previous: ContV sample, Up: 2D samples [Contents][Index]
Command axial draw surfaces of rotation for contour lines. You can draw wire surfaces (‘#’ style) or ones rotated in other directions (‘x’, ‘z’ styles). The sample code is:
light on:alpha on:call 'prepare2d' subplot 2 2 0:title 'Axial plot (default)':rotate 50 60:box axial a subplot 2 2 1:title '"x" style;\".\" style':light on:rotate 50 60:box axial a 'x.' subplot 2 2 2:title '"z" style':light on:rotate 50 60:box axial a 'z' subplot 2 2 3:title '"\#" style':light on:rotate 50 60:box axial a '#'
Previous: Axial sample, Up: 2D samples [Contents][Index]
Command grad draw gradient lines for matrix. The sample code is:
call 'prepare2d' subplot 1 1 0 '':title 'Grad plot':box grad a:dens a '{u8}w{q8}'
Next: Vector field samples, Previous: 2D samples, Up: Examples [Contents][Index]
This section is devoted to visualization of 3D data arrays. 3D means the data which depend on 3 indexes (parameters) like tensor a(i,j,k)=a(x(i),y(j),x(k)), i=1...n, j=1...m, k=1...l or in parametric form {x(i,j,k),y(i,j,k),z(i,j,k),a(i,j,k)}. Most of samples will use the same data for plotting. So, I put its initialization in separate function
func 'prepare3d' new c 61 50 40 '-2*(x^2+y^2+z^4-z^2)+0.2' new d 61 50 40 '1-2*tanh((x+y)*(x+y))' return
Basically, you can put this text after the script. Note, that you need to terminate main script by stop command before defining a function.
• Surf3 sample: | ||
• Surf3C sample: | ||
• Surf3A sample: | ||
• Surf3CA sample: | ||
• Cloud sample: | ||
• Dens3 sample: | ||
• Cont3 sample: | ||
• ContF3 sample: | ||
• Dens projection sample: | ||
• Cont projection sample: | ||
• ContF projection sample: | ||
• TriPlot and QuadPlot: | ||
• Dots sample: | ||
• IFS sample: |
Next: Surf3C sample, Up: 3D samples [Contents][Index]
Command surf3 is one of most suitable (for my opinion) functions to visualize 3D data. It draw the isosurface(s) – surface(s) of constant amplitude (3D analogue of contour lines). You can draw wired isosurfaces if specify ‘#’ style. The sample code is:
call 'prepare3d' light on:alpha on subplot 2 2 0:title 'Surf3 plot':rotate 50 60:box surf3 c subplot 2 2 1:title '"\#" style':rotate 50 60:box surf3 c '#' subplot 2 2 2:title '"." style':rotate 50 60:box surf3 c '.'
Next: Surf3A sample, Previous: Surf3 sample, Up: 3D samples [Contents][Index]
Command surf3c is similar to surf3 but its coloring is determined by another data. The sample code is:
call 'prepare3d' title 'Surf3C plot':rotate 50 60:light on:alpha on:box surf3c c d
Next: Surf3CA sample, Previous: Surf3C sample, Up: 3D samples [Contents][Index]
Command surf3a is similar to surf3 but its transparency is determined by another data. The sample code is:
call 'prepare3d' title 'Surf3A plot':rotate 50 60:light on:alpha on:box surf3a c d
Next: Cloud sample, Previous: Surf3A sample, Up: 3D samples [Contents][Index]
Command surf3ca is similar to surf3 but its color and transparency is determined by another data. The sample code is:
call 'prepare3d' title 'Surf3CA plot':rotate 50 60:light on:alpha on:box surf3a c d c
Next: Dens3 sample, Previous: Surf3CA sample, Up: 3D samples [Contents][Index]
Command cloud draw cloud-like object which is less transparent for higher data values. Similar plot can be created using many (about 10-20) Surf3A(a,a)
isosurfaces. The sample code is:
call 'prepare3d' subplot 2 2 0:title 'Cloud plot':rotate 50 60:alpha on:box cloud c 'wyrRk' subplot 2 2 1:title '"i" style':rotate 50 60:box cloud c 'iwyrRk' subplot 2 2 2:title '"." style':rotate 50 60:box cloud c '.wyrRk' subplot 2 2 3:title 'meshnum 10':rotate 50 60:box cloud c 'wyrRk'; meshnum 10
Next: Cont3 sample, Previous: Cloud sample, Up: 3D samples [Contents][Index]
Command dens3 draw just usual density plot but at slices of 3D data. The sample code is:
call 'prepare3d' title 'Dens3 sample':rotate 50 60:alpha on:alphadef 0.7 origin 0 0 0:box:axis '_xyz' dens3 c 'x':dens3 c ':y':dens3 c 'z'
Next: ContF3 sample, Previous: Dens3 sample, Up: 3D samples [Contents][Index]
Command cont3 draw just usual contour lines but at slices of 3D data. The sample code is:
call 'prepare3d' title 'Cont3 sample':rotate 50 60:box cont3 c 'x':cont3 c:cont3 c 'z'
Next: Dens projection sample, Previous: Cont3 sample, Up: 3D samples [Contents][Index]
Command contf3 draw just usual filled contours but at slices of 3D data. The sample code is:
call 'prepare3d' title 'Cont3 sample':rotate 50 60:box:light on contf3 c 'x':contf3 c:contf3 c 'z' cont3 c 'xk':cont3 c 'k':cont3 c 'zk'
Next: Cont projection sample, Previous: ContF3 sample, Up: 3D samples [Contents][Index]
Functions densz, densy, densx draw density plot on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field. The sample code is:
call 'prepare3d' title 'Dens[XYZ] sample':rotate 50 60:box densx {sum c 'x'} '' -1 densy {sum c 'y'} '' 1 densz {sum c 'z'} '' -1
Next: ContF projection sample, Previous: Dens projection sample, Up: 3D samples [Contents][Index]
Functions contz, conty, contx draw contour lines on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field. The sample code is:
call 'prepare3d' title 'Cont[XYZ] sample':rotate 50 60:box contx {sum c 'x'} '' -1 conty {sum c 'y'} '' 1 contz {sum c 'z'} '' -1
Next: TriPlot and QuadPlot, Previous: Cont projection sample, Up: 3D samples [Contents][Index]
Functions contfz, contfy, contfx draw filled contours on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field. The sample code is:
call 'prepare3d' title 'ContF[XYZ] sample':rotate 50 60:box contfx {sum c 'x'} '' -1 contfy {sum c 'y'} '' 1 contfz {sum c 'z'} '' -1
Next: Dots sample, Previous: ContF projection sample, Up: 3D samples [Contents][Index]
Command triplot and quadplot draw set of triangles (or quadrangles for QuadPlot
) for irregular data arrays. Note, that you have to provide not only vertexes, but also the indexes of triangles or quadrangles. I.e. perform triangulation by some other library. The sample code is:
list q 0 1 2 3 | 4 5 6 7 | 0 2 4 6 | 1 3 5 7 | 0 4 1 5 | 2 6 3 7 list xq -1 1 -1 1 -1 1 -1 1 list yq -1 -1 1 1 -1 -1 1 1 list zq -1 -1 -1 -1 1 1 1 1 light on subplot 2 2 0:title 'QuadPlot sample':rotate 50 60 quadplot q xq yq zq 'yr' quadplot q xq yq zq '#k' subplot 2 2 2:title 'QuadPlot coloring':rotate 50 60 quadplot q xq yq zq yq 'yr' quadplot q xq yq zq '#k' list t 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0 list yt -1 -1 1 0 list zt -1 -1 -1 1 subplot 2 2 1:title 'TriPlot sample':rotate 50 60 triplot t xt yt zt 'b' triplot t xt yt zt '#k' subplot 2 2 3:title 'TriPlot coloring':rotate 50 60 triplot t xt yt zt yt 'cb' triplot t xt yt zt '#k' tricont t xt yt zt 'B'
Next: IFS sample, Previous: TriPlot and QuadPlot, Up: 3D samples [Contents][Index]
Command dots is another way to draw irregular points. Dots
use color scheme for coloring (see Color scheme). The sample code is:
new t 2000 'pi*(rnd-0.5)':new f 2000 '2*pi*rnd' copy x 0.9*cos(t)*cos(f):copy y 0.9*cos(t)*sin(f):copy z 0.6*sin(t):copy c cos(2*t) subplot 2 2 0:title 'Dots sample':rotate 50 60 box:dots x y z alpha on subplot 2 2 1:title 'add transparency':rotate 50 60 box:dots x y z c subplot 2 2 2:title 'add colorings':rotate 50 60 box:dots x y z x c subplot 2 2 3:title 'Only coloring':rotate 50 60 box:tens x y z x ' .'
Previous: Dots sample, Up: 3D samples [Contents][Index]
Commands ifs2d and ifs3d generate points for fractals using iterated function system in 2d and 3d cases correspondingly. The sample codes are:
list A [0.33,0,0,0.33,0,0,0.2] [0.33,0,0,0.33,0.67,0,0.2] [0.33,0,0,0.33,0.33,0.33,0.2]\ [0.33,0,0,0.33,0,0.67,0.2] [0.33,0,0,0.33,0.67,0.67,0.2] ifs2d fx fy A 100000 subplot 1 1 0 '<_':title 'IFS 2d sample' ranges fx fy:axis plot fx fy 'r#o ';size 0.05
list A [0,0,0,0,.18,0,0,0,0,0,0,0,.01] [.85,0,0,0,.85,.1,0,-0.1,0.85,0,1.6,0,.85]\ [.2,-.2,0,.2,.2,0,0,0,0.3,0,0.8,0,.07] [-.2,.2,0,.2,.2,0,0,0,0.3,0,0.8,0,.07] ifs3d f A 100000 title 'IFS 3d sample':rotate 50 60 ranges f(0) f(1) f(2):axis:box dots f(0) f(1) f(2) 'G#o';size 0.05
Next: Hints, Previous: 3D samples, Up: Examples [Contents][Index]
Vector field visualization (especially in 3d case) is more or less complex task. MathGL provides 3 general types of plots: vector field itself (Vect
), flow threads (Flow
), and flow pipes with radius proportional to field amplitude (Pipe
).
However, the plot may look tangly – there are too many overlapping lines. I may suggest 2 ways to solve this problem. The first one is to change SetMeshNum
for decreasing the number of hachures. The second way is to use the flow thread chart Flow
, or possible many flow thread from manual position (FlowP
). Unfortunately, I don’t know any other methods to visualize 3d vector field. If you know any, e-mail me and I shall add it to MathGL.
Most of samples will use the same data for plotting. So, I put its initialization in separate function
func 'prepare2v' new a 20 30 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' new b 20 30 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' return func 'prepare3v' define $1 pow(x*x+y*y+(z-0.3)*(z-0.3)+0.03,1.5) define $2 pow(x*x+y*y+(z+0.3)*(z+0.3)+0.03,1.5) new ex 10 10 10 '0.2*x/$1-0.2*x/$2' new ey 10 10 10 '0.2*y/$1-0.2*y/$2' new ez 10 10 10 '0.2*(z-0.3)/$1-0.2*(z+0.3)/$2' return
Basically, you can put this text after the script. Note, that you need to terminate main script by stop command before defining a function.
• Vect sample: | ||
• Vect3 sample: | ||
• Traj sample: | ||
• Flow sample: | ||
• Pipe sample: | ||
• Dew sample: |
Next: Vect3 sample, Up: Vector field samples [Contents][Index]
Command vect is most standard way to visualize vector fields – it draw a lot of arrows or hachures for each data cell. It have a lot of options which can be seen on the figure (and in the sample code). Vect
use color scheme for coloring (see Color scheme). The sample code is:
call 'prepare2v' subplot 3 2 0 '':title 'Vect plot (default)':box vect a b subplot 3 2 1 '':title '"." style; "=" style':box vect a b '.=' subplot 3 2 2 '':title '"f" style':box vect a b 'f' subplot 3 2 3 '':title '">" style':box vect a b '>' subplot 3 2 4 '':title '"<" style':box vect a b '<' call 'prepare3v' subplot 3 2 5:title '3d variant':rotate 50 60:box vect ex ey ez
Next: Traj sample, Previous: Vect sample, Up: Vector field samples [Contents][Index]
Command vect3 draw just usual vector field plot but at slices of 3D data. The sample code is:
origin 0 0 0:call 'prepare3v' subplot 2 1 0:title 'Vect3 sample':rotate 50 60 box:axis '_xyz' vect3 ex ey ez 'x':vect3 ex ey ez:vect3 ex ey ez 'z' subplot 2 1 1:title '"f" style':rotate 50 60 box:axis '_xyz' vect3 ex ey ez 'fx':vect3 ex ey ez 'f':vect3 ex ey ez 'fz' grid3 ex 'Wx':grid3 ex 'W':grid3 ex 'Wz'
Next: Flow sample, Previous: Vect3 sample, Up: Vector field samples [Contents][Index]
Command traj is 1D analogue of Vect
. It draw vectors from specified points. The sample code is:
call 'prepare1d' subplot 1 1 0 '':title 'Traj plot':box plot x1 y:traj x1 y y1 y2
Next: Pipe sample, Previous: Traj sample, Up: Vector field samples [Contents][Index]
Command flow is another standard way to visualize vector fields – it draw lines (threads) which is tangent to local vector field direction. MathGL draw threads from edges of bounding box and from central slices. Sometimes it is not most appropriate variant – you may want to use FlowP
to specify manual position of threads. Flow
use color scheme for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source). The sample code is:
call 'prepare2v' subplot 2 2 0 '':title 'Flow plot (default)':box flow a b subplot 2 2 1 '':title '"v" style':box flow a b 'v' subplot 2 2 2 '':title 'from edges only':box flow a b '#' call 'prepare3v' subplot 2 2 3:title '3d variant':rotate 50 60:box flow ex ey ez
Next: Dew sample, Previous: Flow sample, Up: Vector field samples [Contents][Index]
Command pipe is similar to flow but draw pipes (tubes) which radius is proportional to the amplitude of vector field. Pipe
use color scheme for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source). The sample code is:
call 'prepare2v' subplot 2 2 0 '':title 'Pipe plot (default)':light on:box pipe a b subplot 2 2 1 '':title '"i" style':box pipe a b 'i' subplot 2 2 2 '':title 'from edges only':box pipe a b '#' call 'prepare3v' subplot 2 2 3:title '3d variant':rotate 50 60:box pipe ex ey ez '' 0.1
Previous: Pipe sample, Up: Vector field samples [Contents][Index]
Command dew is similar to Vect
but use drops instead of arrows. The sample code is:
call 'prepare2v' subplot 1 1 0 '':title 'Dew plot':light on:box dew a b
Next: FAQ, Previous: Vector field samples, Up: Examples [Contents][Index]
In this section I’ve included some small hints and advices for the improving of the quality of plots and for the demonstration of some non-trivial features of MathGL library. In contrast to previous examples I showed mostly the idea but not the whole drawing function.
Next: Transparency and lighting, Up: Hints [Contents][Index]
As I noted above, MathGL functions (except the special one, like Clf()) do not erase the previous plotting but just add the new one. It allows one to draw “compound” plots easily. For example, popular Matlab command surfc
can be emulated in MathGL by 2 calls:
Surf(a); Cont(a, "_"); // draw contours at bottom
Here a is 2-dimensional data for the plotting, -1
is the value of z-coordinate at which the contour should be plotted (at the bottom in this example). Analogously, one can draw density plot instead of contour lines and so on.
Another nice plot is contour lines plotted directly on the surface:
Light(true); // switch on light for the surface Surf(a, "BbcyrR"); // select 'jet' colormap for the surface Cont(a, "y"); // and yellow color for contours
The possible difficulties arise in black&white case, when the color of the surface can be close to the color of a contour line. In that case I may suggest the following code:
Light(true); // switch on light for the surface Surf(a, "kw"); // select 'gray' colormap for the surface CAxis(-1,0); // first draw for darker surface colors Cont(a, "w"); // white contours CAxis(0,1); // now draw for brighter surface colors Cont(a, "k"); // black contours CAxis(-1,1); // return color range to original state
The idea is to divide the color range on 2 parts (dark and bright) and to select the contrasting color for contour lines for each of part.
Similarly, one can plot flow thread over density plot of vector field amplitude (this is another amusing plot from Matlab) and so on. The list of compound graphics can be prolonged but I hope that the general idea is clear.
Just for illustration I put here following sample code:
call 'prepare2v' call 'prepare3d' new v 10:fill v -0.5 1:copy d sqrt(a^2+b^2) subplot 2 2 0:title 'Surf + Cont':rotate 50 60:light on:box surf a:cont a 'y' subplot 2 2 1 '':title 'Flow + Dens':light off:box flow a b 'br':dens d subplot 2 2 2:title 'Mesh + Cont':rotate 50 60:box mesh a:cont a '_' subplot 2 2 3:title 'Surf3 + ContF3':rotate 50 60:light on box:contf3 v c 'z' 0:contf3 v c 'x':contf3 v c cut 0 -1 -1 1 0 1.1 contf3 v c 'z' c.nz-1:surf3 c -0.5
Next: Types of transparency, Previous: ``Compound'' graphics, Up: Hints [Contents][Index]
Here I want to show how transparency and lighting both and separately change the look of a surface. So, there is code and picture for that:
call 'prepare2d' subplot 2 2 0:title 'default':rotate 50 60:box surf a subplot 2 2 1:title 'light on':rotate 50 60:box light on:surf a subplot 2 2 3:title 'light on; alpha on':rotate 50 60:box alpha on:surf a subplot 2 2 2:title 'alpha on':rotate 50 60:box light off:surf a
Next: Axis projection, Previous: Transparency and lighting, Up: Hints [Contents][Index]
MathGL library has advanced features for setting and handling the surface transparency. The simplest way to add transparency is the using of command alpha. As a result, all further surfaces (and isosurfaces, density plots and so on) become transparent. However, their look can be additionally improved.
The value of transparency can be different from surface to surface. To do it just use SetAlphaDef
before the drawing of the surface, or use option alpha
(see Command options). If its value is close to 0 then the surface becomes more and more transparent. Contrary, if its value is close to 1 then the surface becomes practically non-transparent.
Also you can change the way how the light goes through overlapped surfaces. The function SetTranspType
defines it. By default the usual transparency is used (‘0’) – surfaces below is less visible than the upper ones. A “glass-like” transparency (‘1’) has a different look – each surface just decreases the background light (the surfaces are commutable in this case).
A “neon-like” transparency (‘2’) has more interesting look. In this case a surface is the light source (like a lamp on the dark background) and just adds some intensity to the color. At this, the library sets automatically the black color for the background and changes the default line color to white.
As example I shall show several plots for different types of transparency. The code is the same except the values of SetTranspType
function:
call 'prepare2d' alpha on:light on transptype 0:clf subplot 2 2 0:rotate 50 60:surf a:box subplot 2 2 1:rotate 50 60:dens a:box subplot 2 2 2:rotate 50 60:cont a:box subplot 2 2 3:rotate 50 60:axial a:box
Next: Adding fog, Previous: Ternary axis, Up: Hints [Contents][Index]
You can easily make 3D plot and draw its x-,y-,z-projections (like in CAD) by using ternary function with arguments: 4 for Cartesian, 5 for Ternary and 6 for Quaternary coordinates. The sample code is:
ranges 0 1 0 1 0 1 new x 50 '0.25*(1+cos(2*pi*x))' new y 50 '0.25*(1+sin(2*pi*x))' new z 50 'x' new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)' new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx light on title 'Projection sample':ternary 4:rotate 50 60 box:axis:grid plot x y z 'r2':surf a '#' xlabel 'X':ylabel 'Y':zlabel 'Z'
Next: Lighting sample, Previous: Axis projection, Up: Hints [Contents][Index]
MathGL can add a fog to the image. Its switching on is rather simple – just use fog function. There is the only feature – fog is applied for whole image. Not to particular subplot. The sample code is:
call 'prepare2d' title 'Fog sample':rotate 50 60:light on fog 1 box:surf a:cont a 'y'
Next: Using primitives, Previous: Adding fog, Up: Hints [Contents][Index]
In contrast to the most of other programs, MathGL supports several (up to 10) light sources. Moreover, the color each of them can be different: white (this is usual), yellow, red, cyan, green and so on. The use of several light sources may be interesting for the highlighting of some peculiarities of the plot or just to make an amusing picture. Note, each light source can be switched on/off individually. The sample code is:
call 'prepare2d' title 'Several light sources':rotate 50 60:light on light 1 0 1 0 'c':light 2 1 0 0 'y':light 3 0 -1 0 'm' box:surf a 'h'
Additionally, you can use local light sources and set to use diffuse reflection instead of specular one (by default) or both kinds. Note, I use attachlight command to keep light settings relative to subplot.
light on: attachlight on call 'prepare2d' subplot 2 2 0:title 'Default':rotate 50 60:box:surf a line -1 -0.7 1.7 -1 -0.7 0.7 'BA' subplot 2 2 1:title 'Local':rotate 50 60 light 0 1 0 1 -2 -1 -1 line 1 0 1 -1 -1 0 'BAO':box:surf a subplot 2 2 2:title 'no diffuse':rotate 50 60 diffuse 0 line 1 0 1 -1 -1 0 'BAO':box:surf a subplot 2 2 3:title 'diffusive only':rotate 50 60 diffuse 0.5:light 0 1 0 1 -2 -1 -1 'w' 0 line 1 0 1 -1 -1 0 'BAO':box:surf a
Next: STFA sample, Previous: Lighting sample, Up: Hints [Contents][Index]
MathGL provide a set of functions for drawing primitives (see Primitives). Primitives are low level object, which used by most of plotting functions. Picture below demonstrate some of commonly used primitives.
subplot 2 2 0 '':title 'Line, Curve, Rhomb, Ellipse' '' -1.5 line -1 -1 -0.5 1 'qAI' curve -0.6 -1 1 1 0 1 1 1 'rA' ball 0 -0.5 '*':ball 1 -0.1 '*' rhomb 0 0.4 1 0.9 0.2 'b#' rhomb 0 0 1 0.4 0.2 'cg@' ellipse 0 -0.5 1 -0.1 0.2 'u#' ellipse 0 -1 1 -0.6 0.2 'm@' light on subplot 2 2 1:title 'Face[xyz]':rotate 50 60:box facex 1 0 -1 1 1 'r':facey -1 -1 -1 1 1 'g':facez 1 -1 -1 -1 1 'b' face -1 -1 1 -1 1 1 1 -1 0 1 1 1 'bmgr' subplot 2 2 3 '':title 'Cone' cone -0.7 -0.3 0 -0.7 0.7 0.5 0.2 0.1 'b':text -0.7 -0.7 'no edges\n(default)' cone 0 -0.3 0 0 0.7 0.5 0.2 0.1 'g@':text 0 -0.7 'with edges\n('\@' style)' cone 0.7 -0.3 0 0.7 0.7 0.5 0.2 0.1 'ry':text 0.7 -0.7 '"arrow" with\n{}gradient' subplot 2 2 2 '':title 'Sphere and Drop' line -0.9 0 1 0.9 0 1 text -0.9 -0.7 'sh=0':drop -0.9 0 0 1 0.5 'r' 0:ball -0.9 0 1 'k' text -0.3 -0.7 'sh=0.33':drop -0.3 0 0 1 0.5 'r' 0.33:ball -0.3 0 1 'k' text 0.3 -0.7 'sh=0.67':drop 0.3 0 0 1 0.5 'r' 0.67:ball 0.3 0 1 'k' text 0.9 -0.7 'sh=1':drop 0.9 0 0 1 0.5 'r' 1:ball 0.9 0 1 'k'
Generally, you can create arbitrary new kind of plot using primitives. For example, MathGL don’t provide any special functions for drawing molecules. However, you can do it using only one type of primitives drop. The sample code is:
alpha on:light on subplot 2 2 0 '':title 'Methane, CH_4':rotate 60 120 sphere 0 0 0 0.25 'k':drop 0 0 0 0 0 1 0.35 'h' 1 2:sphere 0 0 0.7 0.25 'g' drop 0 0 0 -0.94 0 -0.33 0.35 'h' 1 2:sphere -0.66 0 -0.23 0.25 'g' drop 0 0 0 0.47 0.82 -0.33 0.35 'h' 1 2:sphere 0.33 0.57 -0.23 0.25 'g' drop 0 0 0 0.47 -0.82 -0.33 0.35 'h' 1 2:sphere 0.33 -0.57 -0.23 0.25 'g' subplot 2 2 1 '':title 'Water, H{_2}O':rotate 60 100 sphere 0 0 0 0.25 'r':drop 0 0 0 0.3 0.5 0 0.3 'm' 1 2:sphere 0.3 0.5 0 0.25 'g' drop 0 0 0 0.3 -0.5 0 0.3 'm' 1 2:sphere 0.3 -0.5 0 0.25 'g' subplot 2 2 2 '':title 'Oxygen, O_2':rotate 60 120 drop 0 0.5 0 0 -0.3 0 0.3 'm' 1 2:sphere 0 0.5 0 0.25 'r' drop 0 -0.5 0 0 0.3 0 0.3 'm' 1 2:sphere 0 -0.5 0 0.25 'r' subplot 2 2 3 '':title 'Ammonia, NH_3':rotate 60 120 sphere 0 0 0 0.25 'b':drop 0 0 0 0.33 0.57 0 0.32 'n' 1 2 sphere 0.33 0.57 0 0.25 'g':drop 0 0 0 0.33 -0.57 0 0.32 'n' 1 2 sphere 0.33 -0.57 0 0.25 'g':drop 0 0 0 -0.65 0 0 0.32 'n' 1 2 sphere -0.65 0 0 0.25 'g'
Moreover, some of special plots can be more easily produced by primitives rather than by specialized function. For example, Venn diagram can be produced by Error
plot:
list x -0.3 0 0.3:list y 0.3 -0.3 0.3:list e 0.7 0.7 0.7 title 'Venn-like diagram':alpha on error x y e e '!rgb@#o'
You see that you have to specify and fill 3 data arrays. The same picture can be produced by just 3 calls of circle function:
title 'Venn-like diagram':alpha on circle -0.3 0.3 0.7 'rr@' circle 0 -0.3 0.7 'gg@' circle 0.3 0.3 0.7 'bb@'
Of course, the first variant is more suitable if you need to plot a lot of circles. But for few ones the usage of primitives looks easy.
Next: Mapping visualization, Previous: Using primitives, Up: Hints [Contents][Index]
Short-time Fourier Analysis (stfa) is one of informative method for analyzing long rapidly oscillating 1D data arrays. It is used to determine the sinusoidal frequency and phase content of local sections of a signal as it changes over time.
MathGL can find and draw STFA result. Just to show this feature I give following sample. Initial data arrays is 1D arrays with step-like frequency. Exactly this you can see at bottom on the STFA plot. The sample code is:
new a 2000:new b 2000 fill a 'cos(50*pi*x)*(x<-.5)+cos(100*pi*x)*(x<0)*(x>-.5)+\ cos(200*pi*x)*(x<.5)*(x>0)+cos(400*pi*x)*(x>.5)' subplot 1 2 0 '<_':title 'Initial signal' plot a:axis:xlabel '\i t' subplot 1 2 1 '<_':title 'STFA plot' stfa a b 64:axis:ylabel '\omega' 0:xlabel '\i t'
Next: Data interpolation, Previous: STFA sample, Up: Hints [Contents][Index]
Sometime ago I worked with mapping and have a question about its visualization. Let me remember you that mapping is some transformation rule for one set of number to another one. The 1d mapping is just an ordinary function – it takes a number and transforms it to another one. The 2d mapping (which I used) is a pair of functions which take 2 numbers and transform them to another 2 ones. Except general plots (like surfc, surfa) there is a special plot – Arnold diagram. It shows the area which is the result of mapping of some initial area (usually square).
I tried to make such plot in map. It shows the set of points or set of faces, which final position is the result of mapping. At this, the color gives information about their initial position and the height describes Jacobian value of the transformation. Unfortunately, it looks good only for the simplest mapping but for the real multivalent quasi-chaotic mapping it produces a confusion. So, use it if you like :).
The sample code for mapping visualization is:
new a 50 40 'x':new b 50 40 'y':zrange -2 2:text 0 0 '\to' subplot 2 1 0:text 0 1.1 '\{x, y\}' '' -2:box map a b 'brgk' subplot 2 1 1:box text 0 1.1 '\{\frac{x^3+y^3}{2}, \frac{x-y}{2}\}' '' -2 fill a '(x^3+y^3)/2':fill b '(x-y)/2':map a b 'brgk'
Next: Making regular data, Previous: Mapping visualization, Up: Hints [Contents][Index]
There are many functions to get interpolated values of a data array. Basically all of them can be divided by 3 categories:
mglGSpline()
in Global functions);
The usage of first category is rather straightforward and don’t need any special comments.
There is difference in indirect access functions. Function subdata use use step-like interpolation to handle correctly single nan
values in the data array. Contrary, function evaluate use local spline interpolation, which give smoother output but spread nan
values. So, subdata should be used for specific data elements (for example, for given column), and evaluate should be used for distributed elements (i.e. consider data array as some field). Following sample illustrates this difference:
subplot 1 1 0 '':title 'SubData vs Evaluate' new in 9 'x^3/1.1':plot in 'ko ':box new arg 99 '4*x+4' evaluate e in arg off:plot e 'b.'; legend 'Evaluate' subdata s in arg:plot s 'r.';legend 'SubData' legend 2
Example of datagrid usage is done in Making regular data. Here I want to show the peculiarities of refill and gspline functions. Both functions require argument(s) which provide coordinates of the data values, and return rectangular data array which equidistantly distributed in axis range. So, in opposite to evaluate function, refill and gspline can interpolate non-equidistantly distributed data. At this both functions refill and gspline provide continuity of 2nd derivatives along coordinate(s). However, refill is slower but give better (from human point of view) result than global spline gspline due to more advanced algorithm. Following sample illustrates this difference:
new x 10 '0.5+rnd':cumsum x 'x':norm x -1 1 copy y sin(pi*x)/1.5 subplot 2 2 0 '<_':title 'Refill sample' box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:' new r 100:refill r x y:plot r 'r' subplot 2 2 1 '<_':title 'Global spline' box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:' new r 100:gspline r x y:plot r 'r' new y 10 '0.5+rnd':cumsum y 'x':norm y -1 1 copy xx x:extend xx 10 copy yy y:extend yy 10:transpose yy copy z sin(pi*xx*yy)/1.5 alpha on:light on subplot 2 2 2:title '2d regular':rotate 40 60 box:axis:mesh xx yy z 'k' new rr 100 100:refill rr x y z:surf rr new xx 10 10 '(x+1)/2*cos(y*pi/2-1)' new yy 10 10 '(x+1)/2*sin(y*pi/2-1)' copy z sin(pi*xx*yy)/1.5 subplot 2 2 3:title '2d non-regular':rotate 40 60 box:axis:plot xx yy z 'ko ' new rr 100 100:refill rr xx yy z:surf rr
Next: Making histogram, Previous: Data interpolation, Up: Hints [Contents][Index]
Sometimes, one have only unregular data, like as data on triangular grids, or experimental results and so on. Such kind of data cannot be used as simple as regular data (like matrices). Only few functions, like dots, can handle unregular data as is.
However, one can use built in triangulation functions for interpolating unregular data points to a regular data grids. There are 2 ways. First way, one can use triangulation function to obtain list of vertexes for triangles. Later this list can be used in functions like triplot or tricont. Second way consist in usage of datagrid function, which fill regular data grid by interpolated values, assuming that coordinates of the data grid is equidistantly distributed in axis range. Note, you can use options (see Command options) to change default axis range as well as in other plotting functions.
new x 100 '2*rnd-1':new y 100 '2*rnd-1':copy z x^2-y^2 # first way - plot triangular surface for points triangulate d x y title 'Triangulation' rotate 50 60:box:light on triplot d x y z:triplot d x y z '#k' # second way - make regular data and plot it new g 30 30:datagrid g x y z:mesh g 'm'
Next: Nonlinear fitting hints, Previous: Making regular data, Up: Hints [Contents][Index]
Using the hist function(s) for making regular distributions is one of useful fast methods to process and plot irregular data. Hist
can be used to find some momentum of set of points by specifying weight function. It is possible to create not only 1D distributions but also 2D and 3D ones. Below I place the simplest sample code which demonstrate hist usage:
new x 10000 '2*rnd-1':new y 10000 '2*rnd-1':copy z exp(-6*(x^2+y^2)) hist xx x z:norm xx 0 1:hist yy y z:norm yy 0 1 multiplot 3 3 3 2 2 '':ranges -1 1 -1 1 0 1:box:dots x y z 'wyrRk' multiplot 3 3 0 2 1 '':ranges -1 1 0 1:box:bars xx multiplot 3 3 5 1 2 '':ranges 0 1 -1 1:box:barh yy subplot 3 3 2:text 0.5 0.5 'Hist and\n{}MultiPlot\n{}sample' 'a' -3
Next: PDE solving hints, Previous: Making histogram, Up: Hints [Contents][Index]
Nonlinear fitting is rather simple. All that you need is the data to fit, the approximation formula and the list of coefficients to fit (better with its initial guess values). Let me demonstrate it on the following simple example. First, let us use sin function with some random noise:
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)' new in 100 '0.3+sin(2*pi*x)'
and plot it to see that data we will fit
title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
The next step is the fitting itself. For that let me specify an initial values ini for coefficients ‘abc’ and do the fitting for approximation formula ‘a+b*sin(c*x)’
list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
Now display it
plot res 'r':plot in 'b' text -0.9 -1.3 'fitted:' 'r:L' putsfit 0 -1.8 'y = ' 'r' text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
NOTE! the fitting results may have strong dependence on initial values for coefficients due to algorithm features. The problem is that in general case there are several local "optimums" for coefficients and the program returns only first found one! There are no guaranties that it will be the best. Try for example to set ini[3] = {0, 0, 0}
in the code above.
The full sample code for nonlinear fitting is:
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)' new in 100 '0.3+sin(2*pi*x)' list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. ' plot res 'r':plot in 'b' text -0.9 -1.3 'fitted:' 'r:L' putsfit 0 -1.8 'y = ' 'r' text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
Next: Drawing phase plain, Previous: Nonlinear fitting hints, Up: Hints [Contents][Index]
Solving of Partial Differential Equations (PDE, including beam tracing) and ray tracing (or finding particle trajectory) are more or less common task. So, MathGL have several functions for that. There are ray for ray tracing, pde for PDE solving, qo2d for beam tracing in 2D case (see Global functions). Note, that these functions take “Hamiltonian” or equations as string values. And I don’t plan now to allow one to use user-defined functions. There are 2 reasons: the complexity of corresponding interface; and the basic nature of used methods which are good for samples but may not good for serious scientific calculations.
The ray tracing can be done by ray function. Really ray tracing equation is Hamiltonian equation for 3D space. So, the function can be also used for finding a particle trajectory (i.e. solve Hamiltonian ODE) for 1D, 2D or 3D cases. The function have a set of arguments. First of all, it is Hamiltonian which defined the media (or the equation) you are planning to use. The Hamiltonian is defined by string which may depend on coordinates ‘x’, ‘y’, ‘z’, time ‘t’ (for particle dynamics) and momentums ‘p’=p_x, ‘q’=p_y, ‘v’=p_z. Next, you have to define the initial conditions for coordinates and momentums at ‘t’=0 and set the integrations step (default is 0.1) and its duration (default is 10). The Runge-Kutta method of 4-th order is used for integration.
const char *ham = "p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)"; mglData r = mglRay(ham, mglPoint(-0.7, -1), mglPoint(0, 0.5), 0.02, 2);
This example calculate the reflection from linear layer (media with Hamiltonian ‘p^2+q^2-x-1’=p_x^2+p_y^2-x-1). This is parabolic curve. The resulting array have 7 columns which contain data for {x,y,z,p,q,v,t}.
The solution of PDE is a bit more complicated. As previous you have to specify the equation as pseudo-differential operator \hat H(x, \nabla) which is called sometime as “Hamiltonian” (for example, in beam tracing). As previously, it is defined by string which may depend on coordinates ‘x’, ‘y’, ‘z’ (but not time!), momentums ‘p’=(d/dx)/i k_0, ‘q’=(d/dy)/i k_0 and field amplitude ‘u’=|u|. The evolutionary coordinate is ‘z’ in all cases. So that, the equation look like du/dz = ik_0 H(x,y,\hat p, \hat q, |u|)[u]. Dependence on field amplitude ‘u’=|u| allows one to solve nonlinear problems too. For example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2"
. Also you may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)"
or ham = "p^2 + i1*x*(x>0)"
.
Next step is specifying the initial conditions at ‘z’ equal to minimal z-axis value. The function need 2 arrays for real and for imaginary part. Note, that coordinates x,y,z are supposed to be in specified axis range. So, the data arrays should have corresponding scales. Finally, you may set the integration step and parameter k0=k_0. Also keep in mind, that internally the 2 times large box is used (for suppressing numerical reflection from boundaries) and the equation should well defined even in this extended range.
Final comment is concerning the possible form of pseudo-differential operator H. At this moment, simplified form of operator H is supported – all “mixed” terms (like ‘x*p’->x*d/dx) are excluded. For example, in 2D case this operator is effectively H = f(p,z) + g(x,z,u). However commutable combinations (like ‘x*q’->x*d/dy) are allowed for 3D case.
So, for example let solve the equation for beam deflected from linear layer and absorbed later. The operator will have the form ‘"p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)"’ that correspond to equation 1/ik_0 * du/dz + d^2 u/dx^2 + d^2 u/dy^2 + x * u + i (x+z)/2 * u = 0. This is typical equation for Electron Cyclotron (EC) absorption in magnetized plasmas. For initial conditions let me select the beam with plane phase front exp(-48*(x+0.7)^2). The corresponding code looks like this:
new re 128 'exp(-48*(x+0.7)^2)':new im 128 pde a 'p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)' re im 0.01 30 transpose a subplot 1 1 0 '<_':title 'PDE solver' axis:xlabel '\i x':ylabel '\i z' crange 0 1:dens a 'wyrRk' fplot '-x' 'k|' text 0 0.95 'Equation: ik_0\partial_zu + \Delta u + x\cdot u +\ i \frac{x+z}{2}\cdot u = 0\n{}absorption: (x+z)/2 for x+z>0'
The last example is example of beam tracing. Beam tracing equation is special kind of PDE equation written in coordinates accompanied to a ray. Generally this is the same parameters and limitation as for PDE solving but the coordinates are defined by the ray and by parameter of grid width w in direction transverse the ray. So, you don’t need to specify the range of coordinates. BUT there is limitation. The accompanied coordinates are well defined only for smooth enough rays, i.e. then the ray curvature K (which is defined as 1/K^2 = (|r''|^2 |r'|^2 - (r'', r'')^2)/|r'|^6) is much large then the grid width: K>>w. So, you may receive incorrect results if this condition will be broken.
You may use following code for obtaining the same solution as in previous example:
define $1 'p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)' subplot 1 1 0 '<_':title 'Beam and ray tracing' ray r $1 -0.7 -1 0 0 0.5 0 0.02 2:plot r(0) r(1) 'k' axis:xlabel '\i x':ylabel '\i z' new re 128 'exp(-48*x^2)':new im 128 new xx 1:new yy 1 qo2d a $1 re im r 1 30 xx yy crange 0 1:dens xx yy a 'wyrRk':fplot '-x' 'k|' text 0 0.85 'absorption: (x+y)/2 for x+y>0' text 0.7 -0.05 'central ray'
Next: Pulse properties, Previous: PDE solving hints, Up: Hints [Contents][Index]
Here I want say a few words of plotting phase plains. Phase plain is name for system of coordinates x, x', i.e. a variable and its time derivative. Plot in phase plain is very useful for qualitative analysis of an ODE, because such plot is rude (it topologically the same for a range of ODE parameters). Most often the phase plain {x, x'} is used (due to its simplicity), that allows to analyze up to the 2nd order ODE (i.e. x''+f(x,x')=0).
The simplest way to draw phase plain in MathGL is using flow function(s), which automatically select several points and draw flow threads. If the ODE have an integral of motion (like Hamiltonian H(x,x')=const for dissipation-free case) then you can use cont function for plotting isolines (contours). In fact. isolines are the same as flow threads, but without arrows on it. Finally, you can directly solve ODE using ode function and plot its numerical solution.
Let demonstrate this for ODE equation x''-x+3*x^2=0. This is nonlinear oscillator with square nonlinearity. It has integral H=y^2+2*x^3-x^2=Const. Also it have 2 typical stationary points: saddle at {x=0, y=0} and center at {x=1/3, y=0}. Motion at vicinity of center is just simple oscillations, and is stable to small variation of parameters. In opposite, motion around saddle point is non-stable to small variation of parameters, and is very slow. So, calculation around saddle points are more difficult, but more important. Saddle points are responsible for solitons, stochasticity and so on.
So, let draw this phase plain by 3 different methods. First, draw isolines for H=y^2+2*x^3-x^2=Const – this is simplest for ODE without dissipation. Next, draw flow threads – this is straightforward way, but the automatic choice of starting points is not always optimal. Finally, use ode to check the above plots. At this we need to run ode in both direction of time (in future and in the past) to draw whole plain. Alternatively, one can put starting points far from (or at the bounding box as done in flow) the plot, but this is a more complicated. The sample code is:
subplot 2 2 0 '<_':title 'Cont':box axis:xlabel 'x':ylabel '\dot{x}' new f 100 100 'y^2+2*x^3-x^2-0.5':cont f subplot 2 2 1 '<_':title 'Flow':box axis:xlabel 'x':ylabel '\dot{x}' new fx 100 100 'x-3*x^2' new fy 100 100 'y' flow fy fx 'v';value 7 subplot 2 2 2 '<_':title 'ODE':box axis:xlabel 'x':ylabel '\dot{x}' for $x -1 1 0.1 ode r 'y;x-3*x^2' 'xy' [$x,0] plot r(0) r(1) ode r '-y;-x+3*x^2' 'xy' [$x,0] plot r(0) r(1) next
Next: Using MGL parser, Previous: Drawing phase plain, Up: Hints [Contents][Index]
There is common task in optics to determine properties of wave pulses or wave beams. MathGL provide special function pulse which return the pulse properties (maximal value, center of mass, width and so on). Its usage is rather simple. Here I just illustrate it on the example of Gaussian pulse, where all parameters are obvious.
subplot 1 1 0 '<_':title 'Pulse sample' # first prepare pulse itself new a 100 'exp(-6*x^2)' # get pulse parameters pulse b a 'x' # positions and widths are normalized on the number of points. So, set proper axis scale. ranges 0 a.nx-1 0 1 axis:plot a # draw pulse and axis # now visualize found pulse properties define m a.max # maximal amplitude # approximate position of maximum line b(1) 0 b(1) m 'r=' # width at half-maximum (so called FWHM) line b(1)-b(3)/2 0 b(1)-b(3)/2 m 'm|' line b(1)+b(3)/2 0 b(1)+b(3)/2 m 'm|' line 0 0.5*m a.nx-1 0.5*m 'h' # parabolic approximation near maximum new x 100 'x' plot b(0)*(1-((x-b(1))/b(2))^2) 'g'
Next: Using options, Previous: Pulse properties, Up: Hints [Contents][Index]
MGL scripts can contain loops, conditions and user-defined functions. Below I show very simple example of its usage:
title 'MGL parser sample' call 'sample' stop func 'sample' new dat 100 'sin(2*pi*(x+1))' plot dat; xrange 0 1 box:axis:xlabel 'x':ylabel 'y' for $0 -1 1 0.1 if $0<0 line 0 0 -1 $0 'r' else line 0 0 -1 $0 'r' endif next
Next: ``Templates'', Previous: Using MGL parser, Up: Hints [Contents][Index]
Command options allow the easy setup of the selected plot by changing global settings only for this plot. Often, options are used for specifying the range of automatic variables (coordinates). However, options allows easily change plot transparency, numbers of line or faces to be drawn, or add legend entries. The sample function for options usage is:
new a 31 41 '-pi*x*exp(-(y+1)^2-4*x^2)' alpha on:light on subplot 2 2 0:title 'Options for coordinates':rotate 40 60:box surf a 'r';yrange 0 1 surf a 'b';yrange 0 -1 subplot 2 2 1:title 'Option "meshnum"':rotate 40 60:box mesh a 'r'; yrange 0 1 mesh a 'b';yrange 0 -1; meshnum 5 subplot 2 2 2:title 'Option "alpha"':rotate 40 60:box surf a 'r';yrange 0 1; alpha 0.7 surf a 'b';yrange 0 -1; alpha 0.3 subplot 2 2 3 '<_':title 'Option "legend"' fplot 'x^3' 'r'; legend 'y = x^3' fplot 'cos(pi*x)' 'b'; legend 'y = cos \pi x' box:axis:legend 2
Next: Nonlinear fitting hints, Previous: Using options, Up: Hints [Contents][Index]
As I have noted before, the change of settings will influence only for the further plotting commands. This allows one to create “template” function which will contain settings and primitive drawing for often used plots. Correspondingly one may call this template-function for drawing simplification.
For example, let one has a set of points (experimental or numerical) and wants to compare it with theoretical law (for example, with exponent law \exp(-x/2), x \in [0, 20]). The template-function for this task is:
void template(mglGraph *gr) { mglData law(100); // create the law law.Modify("exp(-10*x)"); gr->SetRanges(0,20, 0.0001,1); gr->SetFunc(0,"lg(y)",0); gr->Plot(law,"r2"); gr->Puts(mglPoint(10,0.2),"Theoretical law: e^x","r:L"); gr->Label('x',"x val."); gr->Label('y',"y val."); gr->Axis(); gr->Grid("xy","g;"); gr->Box(); }
At this, one will only write a few lines for data drawing:
template(gr); // apply settings and default drawing from template mglData dat("fname.dat"); // load the data // and draw it (suppose that data file have 2 columns) gr->Plot(dat.SubData(0),dat.SubData(1),"bx ");
A template-function can also contain settings for font, transparency, lightning, color scheme and so on.
I understand that this is obvious thing for any professional programmer, but I several times receive suggestion about “templates” ... So, I decide to point out it here.
Next: Reduce memory usage, Previous: ``Templates'', Up: Hints [Contents][Index]
One can easily create stereo image in MathGL. Stereo image can be produced by making two subplots with slightly different rotation angles. The corresponding code looks like this:
call 'prepare2d' light on subplot 2 1 0:rotate 50 60+1:box:surf a subplot 2 1 1:rotate 50 60-1:box:surf a
Next: Saving and scanning file, Previous: Stereo image, Up: Hints [Contents][Index]
By default MathGL save all primitives in memory, rearrange it and only later draw them on bitmaps. Usually, this speed up drawing, but may require a lot of memory for plots which contain a lot of faces (like cloud, dew). You can use quality function for setting to use direct drawing on bitmap and bypassing keeping any primitives in memory. This function also allow you to decrease the quality of the resulting image but increase the speed of the drawing.
The code for lower memory usage looks like this:
quality 6 # firstly, set to draw directly on bitmap for $1 0 1000 sphere 2*rnd-1 2*rnd-1 0.05 next
Previous: Reduce memory usage, Up: Hints [Contents][Index]
MathGL have possibilities to write textual information into file with variable values by help of save command. This is rather useful for generating an ini-files or preparing human-readable textual files. For example, lets create some textual file
subplot 1 1 0 '<_':title 'Save and scanfile sample' list a 1 -1 0 save 'This is test: 0 -> ',a(0),' q' 'test.txt' 'w' save 'This is test: 1 -> ',a(1),' q' 'test.txt' save 'This is test: 2 -> ',a(2),' q' 'test.txt'
It contents look like
This is test: 0 -> 1 q This is test: 1 -> -1 q This is test: 2 -> 0 q
Note, that I use option ‘w’ at first call of save
to overwrite the contents of the file.
Let assume now that you want to read this values (i.e. [[0,1],[1,-1],[2,0]]) from the file. You can use scanfile for that. The desired values was written using template ‘This is test: %g -> %g q’. So, just use
scanfile a 'test.txt' 'This is test: %g -> %g'
and plot it to for assurance
ranges a(0) a(1):axis:plot a(0) a(1) 'o'
Note, I keep only the leading part of template (i.e. ‘This is test: %g -> %g’ instead of ‘This is test: %g -> %g q’), because there is no important for us information after the second number in the line.
Check that points of the plot are located inside the bounding box and resize the bounding box using ranges function. Check that the data have correct dimensions for selected type of plot. Sometimes the light reflection from flat surfaces (like, dens) can look as if the plot were absent.
Most “new” types of plots can be created by using the existing drawing functions. For example, the surface of curve rotation can be created by a special function torus, or as a parametrically specified surface by surf. See also, Hints. If you can not find a specific type of plot, please e-mail me and this plot will appear in the next version of MathGL library.
The standard way is to use Unicode encoding for the text output. But the MathGL library also has interface for 8-bit (char *) strings with internal conversion to Unicode. This conversion depends on the current locale OS.
There are 3 general ways. First, the point with nan
value as one of the coordinates (including color/alpha range) will never be plotted. Second, special functions define the condition when the points should be omitted (see Cutting). Last, you may change the transparency of a part of the plot by the help of functions surfa, surf3a (see Dual plotting). In last case the transparency is switched on smoothly.
Most of the library was written by one person. This is a result of nearly a year of work (mostly in the evening and on holidays): I spent half a year to write the kernel and half a year to a year on extending, improving the library and writing documentation. This process continues now :). The build system (cmake files) was written mostly by D.Kulagin, and the export to PRC/PDF was written mostly by M.Vidassov.
You can import data by command import and display it by dens function. For example, for black-and-white bitmap you can use the code: import bmp 'fname.png' 'wk':dens bmp 'wk'
.
Just use command write fname.pdf
, which create PDF file if enable-pdf=ON at MathGL configure.
Just use command write fname.tex
, which create LaTeX files with figure itself ‘fname.tex’, with MathGL colors ‘mglcolors.tex’ and main file ‘mglmain.tex’. Last one can be used for viewing image by command like pdflatex mglmain.tex
.
First, you should download new font files from here or from here. Next, you should load the font files into by the following command: loadfont 'fontname'
. Here fontname is the base font name like ‘STIX’. Use loadfont ''
to start using the default font.
Just set a negative value in ticklen. For example, use ticklen -0.1
.
Just use rotatetext off
. Also you can use axis style ‘U’ for disable only tick labels rotation.
Just use aspect nan nan
for each subplot, or at the beginning of the drawing.
Просто используйте код типа clf 'r{A5}'
или подготовьте PNG файл и задайте его в качестве фона рисунка background 'fname.png'
.
Простейший путь состоит в использовании стилей subplot. Однако, вы должны быть осторожны в изменении стиля subplot если вы планируете добавлять colorbar или вращать график – часть графика может стать невидимой.
Yes. Sometimes you may have huge surface and a small set of curves and/or text on the plot. You can use function rasterize just after making surface plot. This will put all plot to bitmap background. At this later plotting will be in vector format. For example, you can do something like following:
surf x y z rasterize # make surface as bitmap axis write 'fname.eps'
Next: Copying This Manual, Previous: Examples, Up: Top [Contents][Index]
This appendix contain the full list of symbols (characters) used by MathGL for setting up plot. Also it contain sections for full list of hot-keys supported by mglview tool and by UDAV program.
• Symbols for styles: | ||
• Hot-keys for mglview: | ||
• Hot-keys for UDAV: |
Next: Hot-keys for mglview, Up: Symbols and hot-keys [Contents][Index]
Below is full list of all characters (symbols) which MathGL use for setting up the plot.
empty line style (see Line styles);
empty color in chart.
set to use new color from palette for each point (not for each curve, as default) in 1D plotting;
set to disable ticks tuning in axis and colorbar;
set to draw grid lines at subticks coordinates too;
define complex variable/expression in MGL script if placed at beginning.
set to use solid marks (see Line styles) or solid error boxes;
set to draw wired plot for axial, surf3, surf3a, surf3c, triplot, quadplot, area, bars, barh, tube, tape, cone, boxs and draw boundary only for circle, ellipse, rhomb;
set to draw also mesh lines for surf, surfc, surfa, dens, densx, densy, densz, dens3, or boundary for chart, facex, facey, facez, rect;
set to draw boundary and box for legend, title, or grid lines for table;
set to draw grid for radar;
set to start flow threads and pipes from edges only for flow, pipe;
set to use whole are for axis range in subplot, inplot;
change text color inside a string (see Font styles);
start comment in MGL scripts or in Command options.
denote parameter of MGL scripts.
set color scheme along 2 coordinates Color scheme.
set to pass long integer number in tick template xtick, ytick, ztick, ctick.
operation in Textual formulas.
denote string in MGL scripts or in Command options.
one of marks (see Line styles);
one of mask for face filling (see Color scheme);
set to start flow threads from 2d array inside data (see flow);
operation in Textual formulas.
one of marks (see Line styles) or kind of error boxes;
one of mask for face filling (see Color scheme);
set to print ‘+’ for positive numbers in axis, label, table;
operation in Textual formulas.
separator for color positions (see Color styles) or items in a list.
solid line style (see Line styles);
one of mask for face filling (see Color scheme);
place entries horizontally in legend;
set to use usual ‘-’ for negative numbers in axis, label, table;
operation in Textual formulas.
one of marks (see Line styles) or kind of error boxes;
set to draw hachures instead of arrows for vect, vect3;
set to use dots instead of faces for cloud, torus, axial, surf3, surf3a, surf3c, surf, surfa, surfc, dens, map;
delimiter of fractional parts for numbers.
operation in Textual formulas.
line dashing style (see Line styles);
stop color scheme parsing (see Color scheme);
range operation in MGL scripts;
separator of commands in MGL scripts.
line dashing style (see Line styles);
one of mask for face filling (see Color scheme);
start of an option in MGL scripts or in Command options.
one of marks (see Line styles);
one of mask for face filling (see Color scheme);
set position of colorbar;
align left in bars, barh, boxplot, cones, candle, ohlc;
operation in Textual formulas.
one of marks (see Line styles);
one of mask for face filling (see Color scheme);
set position of colorbar;
align right in bars, barh, boxplot, cones, candle, ohlc;
operation in Textual formulas.
line dashing style (see Line styles);
one of mask for face filling (see Color scheme);
set to use equidistant columns for table;
set to use color gradient for vect, vect3;
operation in Textual formulas.
set to draw box around text for text and similar functions;
set to draw boundary and fill it for circle, ellipse, rhomb;
set to fill faces for box;
set to draw large semitransparent mark instead of error box for error;
set to draw edges for cone;
set to draw filled boxes for boxs;
reduce text size inside a string (see Font styles);
operation in Textual formulas.
one of marks (see Line styles);
one of mask for face filling (see Color scheme);
set position of colorbar;
set outer position for legend;
inverse default position for axis;
switch to upper index inside a string (see Font styles);
align center in bars, barh, boxplot, cones, candle, ohlc;
operation in Textual formulas.
empty arrow style (see Line styles);
disable drawing of tick labels for axis;
set position of colorbar;
set to draw contours at bottom for cont, contf, contd, contv, tricont;
switch to lower index inside a string (see Font styles).
contain symbols excluded from color scheme parsing (see Color scheme).
contain extended specification of color (see Color styles), dashing (see Line styles) or mask (see Color scheme);
denote special operation in MGL scripts;
denote ’meta-symbol’ for LaTeX like string parsing (see Font styles).
line dashing style (see Line styles);
set to use sharp color scheme (see Color scheme);
set to limit width by subplot width for table;
delimiter in list command;
operation in Textual formulas.
string continuation symbol on next line for MGL scripts.
disable drawing of tick labels for axis and colorbar;
disable first segment in lamerey;
one of mask for face filling (see Color scheme).
line width (see Line styles);
brightness of a color (see Color styles);
precision of numbers in axis, label, table;
kind of smoothing (for digits 1,3,5) in smooth;
digits for a value.
set to draw square, hex- or octo-pyramids instead of cones in cone, cones.
can be hex-digit for color specification if placed inside {} (see Color styles).
arrow style (see Line styles);
set to use absolute position in whole picture for text, colorbar, legend.
set to use absolute position in subplot for text;
dark blue color (see Color styles).
blue color (see Color styles);
bold font face if placed after ‘:’ (see Font styles).
dark cyan color (see Color styles);
align text to center if placed after ‘:’ (see Font styles).
cyan color (see Color styles);
name of color axis;
cosine transform for transform.
arrow style (see Line styles);
one of mask for face filling (see Color scheme).
one of marks (see Line styles) or kind of error boxes;
one of mask for face filling (see Color scheme);
start hex-dash description if placed inside {} (see Line styles).
dark green-yellow color (see Color styles).
green-yellow color (see Color styles).
set fixed format for numbers in axis, label, table;
Fourier transform for transform.
dark green color (see Color styles).
green color (see Color styles).
dark gray color (see Color styles).
gray color (see Color styles);
Hankel transform for transform.
arrow style (see Line styles);
set colorbar position near boundary.
line dashing style (see Line styles);
italic font face if placed after ‘:’ (see Font styles).
set to use inverse values for cloud, pipe, dew;
set to fill only area with y1<y<y2 for region;
inverse Fourier transform for transform.
line dashing style (see Line styles);
one of mask for face filling (see Color scheme).
arrow style (see Line styles).
black color (see Color styles).
dark green-blue color (see Color styles);
align text to left if placed after ‘:’ (see Font styles).
green-blue color (see Color styles).
dark magenta color (see Color styles).
magenta color (see Color styles).
dark sky-blue color (see Color styles).
sky-blue color (see Color styles).
arrow style (see Line styles);
one of mask for face filling (see Color scheme).
one of marks (see Line styles) or kind of error boxes;
one of mask for face filling (see Color scheme);
over-line text if placed after ‘:’ (see Font styles).
dark purple color (see Color styles).
purple color (see Color styles).
dark orange or brown color (see Color styles).
orange color (see Color styles).
dark red color (see Color styles);
align text to right if placed after ‘:’ (see Font styles).
red color (see Color styles).
arrow style (see Line styles);
one of mask for face filling (see Color scheme).
one of marks (see Line styles) or kind of error boxes;
one of mask for face filling (see Color scheme);
start hex-mask description if placed inside {} (see Color scheme);
sine transform for transform.
arrow style (see Line styles);
set to draw text labels for cont, cont3;
name of t-axis (one of ternary axis);
variable in Textual formulas, which usually is varied in range [0,1].
dark blue-violet color (see Color styles);
disable rotation of tick labels for axis.
blue-violet color (see Color styles);
under-line text if placed after ‘:’ (see Font styles);
name of u-axis (one of ternary axis);
variable in Textual formulas, which usually denote array itself.
arrow style (see Line styles);
place text centering on vertical direction for text.
one of marks (see Line styles);
set to draw vectors on flow threads for flow and on segments for lamerey.
bright gray color (see Color styles).
white color (see Color styles);
wired text if placed after ‘:’ (see Font styles);
name of w-axis (one of ternary axis);
arrow style (see Line styles).
one of marks (see Line styles) or kind of error boxes;
name of x-axis or x-direction or 1st dimension of a data array;
start hex-color description if placed inside {} (see Color styles);
style of tape.
dark yellow or gold color (see Color styles).
yellow color (see Color styles);
name of y-axis or y-direction or 2nd dimension of a data array.
name of z-axis or z-direction or 3d dimension of a data array;
style of tape.
Next: Hot-keys for UDAV, Previous: Symbols for styles, Up: Symbols and hot-keys [Contents][Index]
Key | Description |
---|---|
Ctrl-P | Open printer dialog and print graphics. |
Ctrl-W | Close window. |
Ctrl-T | Switch on/off transparency for the graphics. |
Ctrl-L | Switch on/off additional lightning for the graphics. |
Ctrl-Space | Restore default graphics rotation, zoom and perspective. |
F5 | Execute script and redraw graphics. |
F6 | Change canvas size to fill whole region. |
F7 | Stop drawing and script execution. |
Ctrl-F5 | Run slideshow. If no parameter specified then the dialog with slideshow options will appear. |
Ctrl-Comma, Ctrl-Period | Show next/previous slide. If no parameter specified then the dialog with slideshow options will appear. |
Ctrl-Shift-G | Copy graphics to clipboard. |
Alt-P | Export as semitransparent PNG. |
Alt-F | Export as solid PNG. |
Alt-J | Export as JPEG. |
Alt-E | Export as vector EPS. |
Alt-S | Export as vector SVG. |
Alt-L | Export as LaTeX/Tikz image. |
Alt-M | Export as MGLD. |
Alt-D | Export as PRC/PDF. |
Alt-O | Export as OBJ. |
Previous: Hot-keys for mglview, Up: Symbols and hot-keys [Contents][Index]
Key | Description |
---|---|
Ctrl-N | Create new window with empty script. Note, all scripts share variables. So, second window can be used to see some additional information of existed variables. |
Ctrl-O | Open and execute/show script or data from file. You may switch off automatic exection in UDAV properties |
Ctrl-S | Save script to a file. |
Ctrl-P | Open printer dialog and print graphics. |
Ctrl-Z | Undo changes in script editor. |
Ctrl-Shift-Z | Redo changes in script editor. |
Ctrl-X | Cut selected text into clipboard. |
Ctrl-C | Copy selected text into clipboard. |
Ctrl-V | Paste selected text from clipboard. |
Ctrl-A | Select all text in editor. |
Ctrl-F | Show dialog for text finding. |
F3 | Find next occurrence of the text. |
Win-C or Meta-C | Show dialog for new command and put it into the script. |
Win-F or Meta-F | Insert last fitted formula with found coefficients. |
Win-S or Meta-S | Show dialog for styles and put it into the script. Styles define the plot view (color scheme, marks, dashing and so on). |
Win-O or Meta-O | Show dialog for options and put it into the script. Options are used for additional setup the plot. |
Win-N or Meta-N | Replace selected expression by its numerical value. |
Win-P or Meta-P | Select file and insert its file name into the script. |
Win-G or Meta-G | Show dialog for plot setup and put resulting code into the script. This dialog setup axis, labels, lighting and other general things. |
Ctrl-Shift-O | Load data from file. Data will be deleted only at exit but UDAV will not ask to save it. |
Ctrl-Shift-S | Save data to a file. |
Ctrl-Shift-C | Copy range of numbers to clipboard. |
Ctrl-Shift-V | Paste range of numbers from clipboard. |
Ctrl-Shift-N | Recreate the data with new sizes and fill it by zeros. |
Ctrl-Shift-R | Resize (interpolate) the data to specified sizes. |
Ctrl-Shift-T | Transform data along dimension(s). |
Ctrl-Shift-M | Make another data. |
Ctrl-Shift-H | Find histogram of data. |
Ctrl-T | Switch on/off transparency for the graphics. |
Ctrl-L | Switch on/off additional lightning for the graphics. |
Ctrl-G | Switch on/off grid of absolute coordinates. |
Ctrl-Space | Restore default graphics rotation, zoom and perspective. |
F5 | Execute script and redraw graphics. |
F6 | Change canvas size to fill whole region. |
F7 | Stop script execution and drawing. |
F8 | Show/hide tool window with list of hidden plots. |
F9 | Restore status for ’once’ command and reload data. |
Ctrl-F5 | Run slideshow. If no parameter specified then the dialog with slideshow options will appear. |
Ctrl-Comma, Ctrl-Period | Show next/previous slide. If no parameter specified then the dialog with slideshow options will appear. |
Ctrl-W | Open dialog with slideshow options. |
Ctrl-Shift-G | Copy graphics to clipboard. |
F1 | Show help on MGL commands |
F2 | Show/hide tool window with messages and information. |
F4 | Show/hide calculator which evaluate and help to type textual formulas. Textual formulas may contain data variables too. |
Meta-Shift-Up, Meta-Shift-Down | Change view angle \theta. |
Meta-Shift-Left, Meta-Shift-Right | Change view angle \phi. |
Alt-Minus, Alt-Equal | Zoom in/out whole image. |
Alt-Up, Alt-Down, Alt-Right, Alt-Left | Shift whole image. |
Alt-P | Export as semitransparent PNG. |
Alt-F | Export as solid PNG. |
Alt-J | Export as JPEG. |
Alt-E | Export as vector EPS. |
Alt-S | Export as vector SVG. |
Alt-L | Export as LaTeX/Tikz image. |
Alt-M | Export as MGLD. |
Alt-D | Export as PRC/PDF. |
Alt-O | Export as OBJ. |
Next: Index, Previous: Symbols and hot-keys, Up: Top [Contents][Index]
Copyright © 2000,2001,2002 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”.
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work’s title, preceding the beginning of the body of the text.
A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document’s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version’s license notice. These titles must be distinct from any other section titles.
You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled “History” in the various original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements.”
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “History”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Copyright (C) year your name. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''.
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with…Texts.” line with this:
with the Invariant Sections being list their titles, with the Front-Cover Texts being list, and with the Back-Cover Texts being list.
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.
Previous: Copying This Manual, Up: Top [Contents][Index]
Jump to: | A B C D E F G H I J L M N O P Q R S T V W X Y Z Н С Т Ц |
---|
Jump to: | A B C D E F G H I J L M N O P Q R S T V W X Y Z Н С Т Ц |
---|