Engee documentation

Graphing

Plots using Plots

To visualise data, you need to download the Plots package:

using Plots

Let’s consider several typical tasks of plotting graphs using the Plots package:

Build a graph of a single signal - use the Plots package to work with data visualisation and plot your signal.
using Plots # загружает пакет Plots
x = 0:0.01:10 # создает временной вектор от 0 до 10 с шагом 0.01
y = sin.(x) # вычисляется синус для каждого элемента временного вектора (x)
plot(x, y, xlabel="Время", ylabel="Амплитуда", title="График синусоидального сигнала") # строит график синусойды с временной осью на оси x и амплитудой на оси y

After executing the code, you will automatically get a graph of the sine signal:

visualization plot 1

Build plots of multiple signals - use the Plots package to plot multiple signals on one chart.
using Plots
x = 0:0.01:10
y1 = sin.(x)
y2 = cos.(x)
plot(x, y1, label="Signal 1")
plot!(x, y2, label="Signal 2") # используется plot! с восклицательным знаком для добавления нового сигнала на график

After executing the code, you will automatically get two plots of the sine and cosine signals respectively:

visualization plot 2

You can output the signals on separate graphs, then the code will look as follows:

using Plots

x = 0:0.01:10
y1 = sin.(x)
y2 = cos.(x)

plot(
    plot(x, y1, label="Signal 1"),
    plot(x, y2, label="Signal 2"),
    layout = 2 # задается количество графиков, значение не может быть ниже числа описываемых plots (в нашем случае не ниже 2)
)

After executing the code, you will automatically get a graph of the sine and cosine signals:

visualization plot 3

Customise Graph - customise the graph display according to your preferences.
A more detailed list of attributes for graph settings is presented in Attributes.

Suppose there is a graph of a sinusoidal signal:

using Plots
x = 0:0.01:10
y = sin.(x)
plot(x, y, xlabel="Время", ylabel="Амплитуда")

visualization plot 1

You can name a legend on the chart using the label="Legend Name" construct. For example:

using Plots
x = 0:0.01:10
y = sin.(x)
plot(x, y, label="Синусоида", xlabel="Время", ylabel="Амплитуда") # вместо y1 легенда получила имя "Синусоида"

visualization new 1

Legend can be removed completely by specifying legend = false:

using Plots
x = 0:0.01:10
y = sin.(x)
plot(x, y, ylabel="Амплитуда", xlabel="Время", legend = false)

visualization new 2

You can also specify a range of axis values, for example:

using Plots
x = 0:0.01:10
y = sin.(x)
plot(x, y, xlims=(0, 5), ylims=(-1, 1), xlabel="Время", ylabel="Амплитуда")

visualization new 3

This approach does not constrain the data, it only changes the visible range of the graph while leaving the full data set unchanged. To limit the data, you should use filtering, e.g.:

using Plots
x = 0:0.01:10
y = sin.(x)
x_filtered = x[x .<= 5] # фильтруем значения x
y_filtered = y[x .<= 5] # фильтруем значения y
plot(x_filtered, y_filtered, xlabel="Время", ylabel="Амплитуда")

Here, the code is constructed for the first half of the sine waveform only and the x and y arrays correspond to the specified range.

The Plots package has a wide range of possibilities to customise the look of the plot itself, e.g:

using Plots
x = 0:0.01:10
y = sin.(x)
plot(x, y, line=:dashdot, color=:red, linewidth=2, xlabel="Время", ylabel="Амплитуда")

Here the chart line has changed to a dashed line with a dot (line=:dashdot), the colour of the line has changed to red (color=:red), and its width has become equal to two (linewidth=2).

visualization new 4

In some cases it is useful to adjust the data point markers, for example:

using Plots
x = 0:0.1:2π
y = sin.(x)
plot(x, y, xlabel="Время", ylabel="Амплитуда", marker=:circle, markersize=8, markerstrokewidth=2, markerstrokealpha=0.8, color=:blue)

A sinusoid graph is plotted here with axis captions (xlabel, ylabel), markers as circles (marker=:circle), marker size 8 (markersize=8), stroke width 2 (markerstrokewidth=2), stroke transparency 0.8 (markerstrokealpha=0.8), and blue line colour (color=:blue).

visualization new 5

Squares or other supported geometric shapes such as squares can be used instead of circle markers:

visualization new 6

One of the most popular options for chart design is to reduce the number of markers while keeping the line completely intact, for example:

x = 0:0.1:10 # Используем один и тот же шаг
y = sin.(x)

plot(x, y, xlabel="Время", ylabel="Амплитуда", label="Полная синусоида", color=:blue, linewidth=2)
scatter!(x, y, label="Маркеры", color=:red)

The scatter!(x, y, label="Markers", colour=:red) command adds red coloured markers to an existing chart based on the x and y data, with the legend "Markers" displayed.

visualization new 7

Save graph as picture - save the resulting graph using the savefig command to the Engee file browser.
savefig("my_plot.png")

After executing the code, you will get a message about the path of the saved file:

*Output:

"/user/my_plot.png"

A plot plotted using Plots in command line will be displayed in the Graphs window of graphs icon 1 Engee on a separate plot tab:

plots graph 1 -> plots graph

In the Plots package there are several different methods of displaying graphics - backends. Which backend to choose depends on your task. The table below will help you to choose a more suitable method.

Usage of library PlotlyJS.jl to create 3D graphs may cause problems when converting scripts to HTML/PDF formats, as well as when publishing to the community.

Usage of the Plots.jl library with the plotlyjs backend does not cause this problem.

Visualisation requirements Graphics backend

Speed

gr, unicodeplots

Interactivity

plotlyjs

Beauty

plotlyjs, gr

Command line plotting

unicodeplots

Drawing spatial curves

plotlyjs, gr

Building surfaces

gr

Two-dimensional plots

Any backend can handle plotting a two-dimensional curve. To scale the graph and select specific points on the curve, let’s connect the plotlyjs graph display method:

plotlyjs();

The plot function is used to create two-dimensional plots.

If you put a semicolon at the end of the plot command, the command will execute, but the plot will not be shown.
x = [-10:10;];
y = x.^2;
plot(x,y)
Output

plotting 1

To add a graph to an existing graph, add an exclamation mark to make plot!(). You can sign the axes and graph, add a title, and change the line and background style:

plot!(2x, y, xlabel="X", ylabel="X^2", title="Парабола", linecolor =:red, bg_inside =:yellow, line =:dashdot, label = "X^2")
Output

plotting 2

Spatial curves

With plot you can also plot a graph in three dimensions:

y = x;
z1 = x.^2;
plot(x,y,z1, xlabel="X", ylabel="Y", zlabel="Z", linecolor =:green, label = "X^2")
Output

plotting 3

y = -x;
z2 = x.^2;
plot!(x,y,z2, xlabel="X", ylabel="Y", zlabel="Z", linecolor =:red, label = "Y^2")
Output

plotting 4

Plotting graphs with PlotlyJS

The second way to visualise data is to use an alternative library PlotlyJS.

using PlotlyJS

If you have used Plots library before, there may be conflicts of function names. Therefore, we will call the plotting functions as follows:

PlotlyJs.<имя_функции>

One of the disadvantages of PlotlyJS library is the requirement of rigid typing. Thus, you will have to perform additional type conversions to build a surface. But when working with PlotlyJS you don’t need to select and connect backends!

Two-dimensional graphs

To plot a graph, you need to create an object describing the curve, surface, etc. to be plotted. A two-dimensional graph can be plotted using the scatter function scatter, specifying the type - line in the settings.

... mode = "lines"

In this example, the type selected is — line with marker.

line1 = PlotlyJS.scatter(x=2018:2022, y=[7.632, 7.769, 7.809, 7.842, 7.841], mode="lines+markers", name="Finland", line_color="purple");
line2 = PlotlyJS.scatter(x=2018:2022, y=[6.419, 6.300, 6.376, 6.330, 6,125], mode="lines+markers", name= "Brazil", line_width=0.5);

Now you can create an object where parameters of the chart appearance will be set. This approach is convenient if there is a need for a uniform style of charts. The library allows you to use a lot of appearance settings. You can sign the chart, choose the thickness of lines, colours (and the choice of colours can be set in different ways).

layout = PlotlyJS.Layout(title="Gross National Happiness", xaxis_range=[2018, 2022], yaxis_range=[5, 8], paper_bgcolor="RGB(250,249,245)", plot_bgcolor="#F5F3EC");

The plot function is used for plotting graphs. If you want to plot several graphs in one, they should be written as a vector:

PlotlyJS.plot([line1, line2], layout)
Output

plotting 5

Spatial curves

The object for drawing a spatial curve is created by the scatter3d function.

x = [-10.0:10.0;];
cubic = PlotlyJS.scatter3d(x=x, y=-x, z=x.^3, mode="lines");
PlotlyJS.plot(cubic)
Output

plotting 6

Surfaces

Let’s build a surface defined by a paraboloid using the surface function. First we need to make sure that the data types are correct. The coordinates in x and y can be either one-dimensional or two-dimensional arrays. When transposing the vector y = x', the result type is not an array:

println("Тип y = x': " ,typeof(x'));

Therefore, it is important to transform the type of the vector y before constructing the surface:

y = vec(collect(x'));
z = (x.^2).+((x').^2);

Let’s check the data types:

println("Тип x: " ,typeof(x));
println("Тип y: " ,typeof(y));
println("Тип z: " ,typeof(z));
paraboloid = PlotlyJS.surface(x=x, y=y, z=z);
PlotlyJS.plot(paraboloid)
Output

plotting 7