Accelerating the pace of engineering and science

# Documentation Center

• Trial Software

# plot::Density

Density plot

### Use only in the MuPAD Notebook Interface.

This functionality does not run in MATLAB.

## Syntax

```plot::Density(f, x = xmin .. xmax, y = ymin .. ymax, <a = amin .. amax>, options)
plot::Density(A, <x = xmin .. xmax, y = ymin .. ymax>, <a = amin .. amax>, options)
plot::Density(L, <x = xmin .. xmax, y = ymin .. ymax>, <a = amin .. amax>, options)
```

## Description

plot::Density(f(x, y), x = `x_{min}`..`x_{max}` , y = `y_{min}`..`y_{max}` ) generates a regular 2D mesh of rectangles extending from the lower left corner (xmin, ymin) to the upper right corner (xmax, ymax). The rectangle with midpoint (x, y) is colored according to a color scheme based on the "density" value f(x, y).

plot::Density serves for the visualization of 3D data (x, y, f(x, y)) by a 2D plot. Roughly speaking, it corresponds to a colored 3D function graph of the density function f(x, y) viewed from above. However, in contrast to the 3D function graph, plot::Density does not use smooth interpolation ("shading") of the color between adjacent rectangles.

If the density data are provided by an array or matrix A or by a list L, the number of rectangles in the density plot is given automatically by the format of A or L, respectively.

If the density data are given by an expression or function f, the attribute Mesh = [m, n] serves for advising plot::Density to create a grid of m×n rectangles. Alternatively, one may set XMesh = m, YMesh = n.

With the default FillColorType = Dichromatic, the rectangle with density value f(x, y) at the midpoint (x, y) is colored with the color

,

where are the minimal/maximal density values in the graphics and fillcolor, fillcolor2 are the RGB values of the attributes FillColor and FillColor2, respectively. Thus, fillcolor indicates high density values whereas fillcolor2 indicates low density values.

If fmin = fmax, a flat coloring with fillcolor is used.

With FillColorType = Monochrome, the rectangle with density value f(x, y) at the midpoint (x, y) is colored with the color

.

The user may specify a fill color function via FillColorFunction = mycolorfunction to override the density coloring described above. The procedure mycolorfunction will be called with the arguments

mycolorfunction(x, y, f(x, y, a ) a ),

where (x, y) are the midpoints of the rectangles and a is the animation parameter. The color function must return an RGB or RGBa color value.

When density values are specified by an array or a matrix A, the low indices correspond to the lower left corner of the graphics. The high indices correspond to the upper right corner.

Arrays/matrices do not need to be indexed from 1. E.g.,

A = array( `i_{min}` .. `i_{max}` , `j_{min}` .. `j_{max}` , [..density values..])

yields a graphical array with

XMesh = jmax - jmin + 1, YMesh = imax - imin + 1.

If no plot range `x_{min}` .. `x_{max}`, `y_{min}` .. `y_{max}` is specified,

xmin = jmin - 1, xmax = jmax, ymin = imin - 1, ymax = imax

is used.

When density values are specified by a list of lists L, the first entries in the list correspond to the lower left corner of the graphics. The last entries correspond to the upper right corner.

If no plot range `x_{min}` .. `x_{max}`, `y_{min}` .. `y_{max}` is specified,

xmin = 0, xmax = m, ymin = 0, ymax = n

is used, where n is the length of L and m is the (common) length of the sublists in L. All sublists ("rows") must have the same length.

Animations are triggered by specifying a range a = `a_{min}` .. `a_{max}` for a parameter a that is different from the variables x, y. Thus, in animations, both the ranges x = `x_{min}` .. `x_{max}`, y = `y_{min}` .. `y_{max}` as well as the animation range a = `a_{min}` .. `a_{max}` must be specified.

The related plot routine plot::Raster provides a similar functionality. However, plot::Raster does not use an automatic color scheme based on density values. The user must provide RGB or RGBa values instead.

## Attributes

AttributePurposeDefault Value
AffectViewingBoxinfluence of objects on the ViewingBox of a sceneTRUE
AntiAliasedantialiased lines and points?FALSE
Colorthe main colorRGB::Red
DensityDatadensity values for a density plot
DensityFunctiondensity function for a density plot
FillColorcolor of areas and surfacesRGB::Red
FillColor2second color of areas and surfaces for color blendsRGB::CornflowerBlue
FillColorTypesurface filling typesDichromatic
FillColorFunctionfunctional area/surface coloring
Framesthe number of frames in an animation50
Legendmakes a legend entry
LegendTextshort explanatory text for legend
LegendEntryadd this object to the legend?FALSE
LineColorcolor of linesRGB::Blue
LineWidthwidth of lines0.35
LineStylesolid, dashed or dotted lines?Solid
LinesVisiblevisibility of linesFALSE
Meshnumber of sample points[25, 25]
Namethe name of a plot object (for browser and legend)
ParameterEndend value of the animation parameter
ParameterNamename of the animation parameter
ParameterBegininitial value of the animation parameter
ParameterRangerange of the animation parameter
TimeEndend time of the animation10.0
TimeBeginstart time of the animation0.0
TimeRangethe real time span of an animation0.0 .. 10.0
Titleobject title
TitleFontfont of object titles[" sans-serif ", 11]
TitlePositionposition of object titles
TitleAlignmenthorizontal alignment of titles w.r.t. their coordinatesCenter
TitlePositionXposition of object titles, x component
TitlePositionYposition of object titles, y component
VisiblevisibilityTRUE
VisibleAfterobject visible after this time value
VisibleBeforeobject visible until this time value
VisibleFromToobject visible during this time range
VisibleAfterEndobject visible after its animation time ended?TRUE
VisibleBeforeBeginobject visible before its animation time starts?TRUE
XMaxfinal value of parameter "x"
XMeshnumber of sample points for parameter "x"25
XMininitial value of parameter "x"
XNamename of parameter "x"
XRangerange of parameter "x"
YMaxfinal value of parameter "y"
YMeshnumber of sample points for parameter "y"25
YMininitial value of parameter "y"
YNamename of parameter "y"
YRangerange of parameter "y"

## Examples

### Example 1

We generate a density plot:

```p := plot::Density(cos(x^2 + y^2), x = -3..3, y = -2..2,
Mesh = [60, 40]):```

The plot object is rendered:

`plot(p, Axes = Frame):`

This turns into a black and white graphics when suitable colors are specified:

```plot(plot::Scene2d(p, FillColor = RGB::White,
FillColor2 = RGB::Black),
plot::Scene2d(p, FillColor = RGB::Black,
FillColor2 = RGB::White),
Width = 120*unit::mm, Height = 45*unit::mm,
Layout = Horizontal, Axes = Frame):```

`delete p:`

### Example 2

We demonstrate the use of a user-defined color function:

```mycolor := proc(x, y, f)
begin
if   f >=  2/3 then RGB::Red
elif f >=  1/3 then RGB::Orange;
elif f >=   0  then RGB::Yellow;
elif f >= -1/3 then RGB::BlueLight;
elif f >= -2/3 then RGB::Blue;
else RGB::SlateBlueDark;
end_if;
end_proc:
plot(plot::Density(cos(x^2 + y^2), x = -3..3, y = -2..2,
Mesh = [60, 40],
FillColorFunction = mycolor),
Axes = Frame):```

`delete mycolor:`

### Example 3

In this example, we demonstrate how plot::Density can be used to plot gray data from an external source. Assume, there is an external PortableGrayMap text file Norton.pgm containing data such as

```P2
240 180
255
249 237 228 231 245 218 229 195 ...
```

The first line contains the "magic value" P2 indicating that this is a PGM text file. The second line contains the pixel width and pixel height of the picture. The number 255 in the third line is the scale of the following gray values.

The remaining data consist of integers between 0 (black) and 255 (white), each representing the gray value of a pixel (row by row).

We import the text data via import::readdata:

`graydata := import::readdata("Norton.pgm", NonNested):`

This is a long list of all data items in the file. We extract the 4 items in the first three lines:

`[magicvalue, xmesh, ymesh, maxgray] := graydata[1..4]`

We delete the header from the pixel data. (If there are comments in the PGM file, they must be deleted, too).

```for i from 1 to 4 do
delete graydata[1];
end_for:```

We transform the plain data list to a nested list containing the gray data of the rows as sublists. (The call to level is not really necessary, but it speeds up the conversion considerably on the interactive level.)

`L := level([graydata[(i - 1)*xmesh + 1 .. i*xmesh] \$ i=1..ymesh], 1):`

This list can be passed to plot::Density:

```plot(plot::Density(L, FillColor = RGB::White,
FillColor2 = RGB::Black),
Width = 80*unit::mm, Height = 60*unit::mm):```

The image is upside down, because the PGM files stores the pixel data row by row in the usual reading order starting with the upper left corner of the image. The MuPAD® routine plot::Density, however, follows the mathematical orientation of the coordinate axes, i.e., the first pixel value is interpreted as the lower left corner of the image. We have to re-order the rows in the graydata list via revert:

```plot(plot::Density(revert(L), FillColor = RGB::White,
FillColor2= RGB::Black),
Width = 80*unit::mm, Height = 60*unit::mm):```

The routines import::readbitmap and plot::Raster provide an alternative way to import and display the bitmap image. See the help page of plot::Raster for examples. This, however, takes more memory, because the bitmap data are imported as RGB color values, whereas only density values (gray data) are needed for plot::Density.

`delete graydata, magicvalue, xmesh, ymesh, maxgray, i, L:`

### Example 4

The Mandelbrot set is one of the best-known fractals. It arises when considering the iteration zn + 1 = zn2 + c, z0 = 0 in the complex plane. For sufficiently large values |c| of the complex parameter c, the sequence zn diverges to infinity; it converges for sufficiently small values of |c|. The boundary of the region of those c values that lead to divergence of zn is of particular interest: this border is highly complicated and of a fractal nature.

In particular, it is known that the series zn diverges to infinity, whenever one of the iterates satisfies |zn| > 2. This fact is used by the following procedure f as stopping criterion. The return value provides information, how many iterates z0, …, zn it takes to escape from the region |z| ≤ 2 of (potential) convergence. These data are to be used to color the complex c plane (i.e., the (x,y) plane) by a density plot:

```f := proc(x, y)
local c, z, n;
begin
c := x + I*y:
z := 0.0:
for n from 0 to 100 do
z := z^2 + c:
if abs(z) > 2 then
break;
end_if;
end_for:
if n < 70 then
n mod 5;
else n - 70;
end_if;
end_proc:```

Depending on your computer, the following computations may take some time. On a very fast machine, you can increase the following values of xmesh, ymesh. This will use up more computing time but will lead to better graphical results:

`xmesh :=  100: ymesh :=  100:`

The following region in the x-y plane is to be considered:

```xmin[1] := -2.0: xmax[1] := 0.5:
ymin[1] := -1.2: ymax[1] := 1.2:```

The region xmin1xxmax1, ymin1yymax1 is divided into xmesh×ymesh rectangles. Each rectangle is colored by a density plot according to the "escape times" computed by the procedure f. This procedure can be passed directly to plot::Density:

```p1 := plot::Density(f, x = xmin[1].. xmax[1],
y = ymin[1] .. ymax[1],
Mesh = [xmesh, ymesh],
FillColor = RGB::Black,
FillColor2 = RGB::Red):```

In addition, a rectangle is produced that indicates a region that is to be magnified in the following:

```xmin[2] := -0.24: xmax[2] := -0.01:
ymin[2] :=  0.63: ymax[2] :=  0.92:
r1 := plot::Rectangle(xmin[2] .. xmax[2], ymin[2] .. ymax[2],
LineColor = RGB::White):```
`plot(p1, r1):`

The density values of the blow-up are not computed directly by plot::Density. They are computed separately and stored in an array A:

```dx := (xmax[2] - xmin[2])/xmesh:
dy := (ymax[2] - ymin[2])/ymesh:
A := array(1..ymesh, 1..xmesh,
[[f(xmin[2]+ (j - 1/2)*dx, ymin[2] + (i - 1/2)*dy)
\$ j = 1..xmesh] \$ i = 1..ymesh]):
p2 := plot::Density(A, x = xmin[2] .. xmax[2], y = ymin[2] .. ymax[2],
FillColor = RGB::Black, FillColor2 = RGB::Red):```

In addition, a further rectangle is produced to indicate a region of interest to be blown up lateron:

```xmin[3] := -0.045: xmax[3] := -0.015:
ymin[3] :=  0.773: ymax[3] :=  0.815:
r2 := plot::Rectangle(xmin[3] .. xmax[3], ymin[3] .. ymax[3],
LineColor = RGB::White):```
`plot(p2, r2):`

The density values of the next blow-up are again computed separately and stored in a nested list L:

```dx := (xmax[3] - xmin[3])/xmesh:
dy := (ymax[3] - ymin[3])/ymesh:
L := [[f(xmin[3] + (j - 1/2)*dx, ymin[3] + (i - 1/2)*dy)
\$ j= 1..xmesh] \$ i = 1..ymesh]:
p3 := plot::Density(L, x = xmin[3] .. xmax[3], y = ymin[3] .. ymax[3],
FillColor = RGB::Black, FillColor2 = RGB::Red):```
`plot(p3):`

The density objects are to be placed in a single graphics. It consists of the Mandelbrot set p1 as computed above and of modifications of the density plots p2 and p3. Redefining the attributes XRange, YRange, we move p2, p3 to places in the x-y plane where they are not overlapped by p1. Note that this does not change the graphical content of p2, p3, because it is given by the data A and L, respectively, which remain unchanged. (If the ranges were changed in p1, another plot call of p1 would call the procedure f at different points of the plane resulting in a different graphics.)

```p2::XRange :=  0.60 .. 1.60: p2::YRange :=  0.05 ..  1.15:
p3::XRange :=  0.60 .. 1.60: p3::YRange := -1.15 .. -0.05:```

The Mandelbrot set and the two blow-ups are placed in one scene. In addition, some arrows are added to indicate the origin of the blow-ups. Note that it is quite important here that the arrows are passed to the plot command after the density plots. Otherwise, they would be hidden by the density plots: graphical objects are painted in the ordering in which they are passed to plot:

```plot(p1, p2, p3,
plot::Arrow2d([(xmin[2] + xmax[2])/2,
(ymin[2] + ymax[2])/2],
[(p2::XMin + p2::XMax)/2,
(p2::YMin + p2::YMax)/2],
LineColor = RGB::Blue),
plot::Arrow2d([1.50, 0.65],
[(p3::XMin + p3::XMax)/2,
(p3::YMin + p3::YMax)/2],
LineColor = RGB::Blue)
):```

```delete f, xmesh, ymesh, xmin, xmax, ymin, ymax,
dx, dy, p1, p2, p3, r1, r2, A, L:```

## Parameters

 f The density values: an arithmetical expression in 2 variables x, y and the animation parameter a. Alternatively, a procedure that accepts 2 input parameters x, y or 3 input parameters x, y, a and returns a real density value. f is equivalent to the attribute DensityFunction. x Name of the horizontal variable: an identifier or an indexed identifier. x is equivalent to the attribute XName. xmin .. xmax The range of the horizontal variable: xmin, xmax must be numerical real value or expressions of the animation parameter a. xmin .. xmax is equivalent to the attributes XRange, XMin, XMax. y Name of the vertical variable: an identifier or an indexed identifier. y is equivalent to the attribute YName. ymin .. ymax The range of the vertical variable: ymin, ymax must be numerical real value or expressions of the animation parameter a. ymin .. ymax is equivalent to the attributes YRange, YMin, YMax. A An array of domain type DOM_ARRAY or a matrix of category Cat::Matrix (e.g., of type matrix or densematrix) providing numerical density values or expressions of the animation parameter a. Rows/columns of the array, respectively matrix, correspond to rows/columns of the graphical array. A is equivalent to the attribute DensityData. L A list of lists of numerical density values or expressions of the animation parameter a. Each sublist of L represents a row of the graphical array. The number of sublists in L yields the value of the attribute XMesh. The (common) length of the sublists yields the value of the attribute YMesh. L is equivalent to the attribute DensityData. a Animation parameter, specified as a = amin..amax, where amin is the initial parameter value, and amax is the final parameter value.