The Structure of Graphics and Sound

The Structure of Graphics
"Graphics and Sound" discusses how to use functions like Plot and ListPlot to plot graphs of functions and data. This tutorial discusses how the Wolfram Language represents such graphics, and how you can program the Wolfram Language to create more complicated images.
The basic idea is that the Wolfram Language represents all graphics in terms of a collection of graphics primitives. The primitives are objects like Point, Line, and Polygon, which represent elements of a graphical image, as well as directives such as RGBColor and Thickness.
This generates a plot of a list of points:
InputForm shows how the Wolfram Language represents the graphics. Each point is represented as a coordinate in a Point graphics primitive. All the various graphics options used in this case are also given:
Each complete piece of graphics in the Wolfram Language is represented as a graphics object. There are several different kinds of graphics object, corresponding to different types of graphics. Each kind of graphics object has a definite head that identifies its type.
general twodimensional graphics
general threedimensional graphics
Graphics objects in the Wolfram Language.
The functions like Plot and ListPlot discussed in "The Structure of Graphics and Sound" all work by building up Wolfram Language graphics objects and then displaying them.
You can create other kinds of graphical images in the Wolfram Language by building up your own graphics objects. Since graphics objects in the Wolfram Language are just symbolic expressions, you can use all the standard Wolfram Language functions to manipulate them.
Graphics objects are automatically formatted by the Wolfram System front end as graphics upon output. Graphics may also be printed as a side effect using the Print command.
The Graphics object is computed by the Wolfram Language, but its output is suppressed by the semicolon:
A side effect output can be generated using the Print command. It has no Out[] label because it is a side effect:
display a graphics object with new options specified by opts
display several graphics objects combined using the options from g1
display several graphics objects with new options specified by opts
Displaying graphics objects.
Show can be used to change the options of an existing graphic or to combine multiple graphics.
This uses Show to adjust the Background option of an existing graphic:
This uses Show to combine two graphics. The values used for PlotRange and other options are based upon those which were set for the first graphic:
Here, new options are specified for the entire graphic:
Graphics directives
Examples: RGBColor, Thickness
Graphics options
Local and global ways to modify graphics.
Given a particular list of graphics primitives, the Wolfram Language provides two basic mechanisms for modifying the final form of graphics you get. First, you can insert into the list of graphics primitives certain graphics directives, such as RGBColor, which modify the subsequent graphical elements in the list. In this way, you can specify how a particular set of graphical elements should be rendered.
This creates a twodimensional graphics object that contains the Polygon graphics primitive:
InputForm shows the complete graphics object:
This takes the graphics primitive created above and adds the graphics directives RGBColor and EdgeForm:
By inserting graphics directives, you can specify how particular graphical elements should be rendered. Often, however, you want to make global modifications to the way a whole graphics object is rendered. You can do this using graphics options.
By adding the graphics option Frame you can modify the overall appearance of the graphics:
InputForm shows that the option was introduced into the resulting Graphics object:
You can specify graphics options in Show. As a result, it is straightforward to take a single graphics object and show it with many different choices of graphics options.
Notice however that Show always returns the graphics objects it has displayed. If you specify graphics options in Show, then these options are automatically inserted into the graphics objects that Show returns. As a result, if you call Show again on the same objects, the same graphics options will be used, unless you explicitly specify other ones. Note that in all cases new options you specify will overwrite ones already there.
give a list of all graphics options for a graphics object
give the setting for a particular option
Finding the options for a graphics object.
Some graphics options can be used as options to visualization functions that generate graphics. Options which can take the right-hand side of Automatic are sometimes resolved into specific values by the visualization functions.
Here is a plot:
The Wolfram Language uses an internal algorithm to compute an explicit value for PlotRange in the resulting graphic:
translate objects specified by graphics options into lists of explicit graphics primitives
Finding the complete form of a piece of graphics.
When you use a graphics option such as Axes, the Wolfram System front end automatically draws objects such as axes that you have requested. The objects are represented merely by the option values rather than by a specific list of graphics primitives. Sometimes, however, you may find it useful to represent these objects as the equivalent list of graphics primitives. The function FullGraphics gives the complete list of graphics primitives needed to generate a particular plot, without any options being used.
This plots a list of values:
FullGraphics yields a graphics object that includes graphics primitives representing axes and so on:
TwoDimensional Graphics Elements
point at position x, y
line through the points {x1,y1}, {x2,y2},
filled rectangle
filled polygon with the specified list of corners
circle with radius r centered at x, y
filled disk with radius r centered at x, y
rectangular array of gray levels between 0 and 1
the text of expr, centered at x, y (see "Graphics Primitives for Text")
Basic twodimensional graphics elements.
Here is a line primitive:
This shows the line as a twodimensional graphics object:
This redisplays the line, with axes added:
You can combine graphics objects that you have created explicitly from graphics primitives with ones that are produced by functions like Plot.
This produces an ordinary Wolfram System plot:
This combines the plot with the sawtooth picture made above:
You can combine different graphical elements simply by giving them in a list. In twodimensional graphics, the Wolfram System will render the elements in exactly the order you give them. Later elements are therefore effectively drawn on top of earlier ones.
Here are two blue Rectangle graphics elements:
This draws the rectangles on top of the line that was defined above:
The Polygon graphics primitive takes a list of , coordinates, corresponding to the corners of a polygon. The Wolfram System joins the last corner with the first one, and then fills the resulting area.
Here are the coordinates of the corners of a regular pentagon:
This displays the pentagon. With the default choice of aspect ratio, the pentagon looks somewhat squashed:
a multipoint consisting of points at pt1, pt2,
a multiline consisting of lines line1, line2,
a multipolygon consisting of polygons poly1, poly2,
Primitives which can take multiple elements.
A large number of points can be represented by putting a list of coordinates inside of a single Point primitive. Similarly, a large number of lines or polygons can be represented as a list of coordinate lists. This representation is efficient and can generally be rendered more quickly by the Wolfram System front end. Graphics directives such as RGBColor apply uniformly to the entire set of primitives.
This creates a multipolygon based upon the set of coordinates defined previously:
Here is a multipoint that is colored blue:
a circle with radius r centered at the point {x,y}
an ellipse with semiaxes rx and ry
a circular arc
an elliptical arc
, etc.
filled disks
Circles and disks.
This shows two circles with radius 2:
This shows a sequence of disks with progressively larger semiaxes in the direction, and progressively smaller ones in the direction:
The Wolfram System allows you to generate arcs of circles and segments of ellipses. In both cases, the objects are specified by starting and finishing angles. The angles are measured counterclockwise in radians with zero corresponding to the positive direction.
This draws a 149° wedge centered at the origin:
array of gray levels between 0 and 1
array of gray levels with opacity between 0 and 1
array of rgb values between 0 and 1
array of rgb values with opacity between 0 and 1
array of gray levels between zmin and zmax drawn in the rectangle defined by {xmin,ymin} and {xmax,ymax}
Rasterbased graphics elements.
Here is a 4×4 array of values between 0 and 1:
This uses the array of values as gray levels in a raster:
This shows two overlapping copies of the raster:
The ColorFunction option can be used to change the default way in which a Raster is colored:
Graphics Directives and Options
When you set up a graphics object in the Wolfram Language, you typically give a list of graphical elements. You can include in that list graphics directives which specify how subsequent elements in the list should be rendered.
In general, the graphical elements in a particular graphics object can be given in a collection of nested lists. When you insert graphics directives in this kind of structure, the rule is that a particular graphics directive affects all subsequent elements of the list it is in, together with all elements of sublists that may occur. The graphics directive does not, however, have any effect outside the list it is in.
The first sublist contains the graphics directive GrayLevel:
Only the rectangle in the first sublist is affected by the GrayLevel directive:
gray level between 0 (black) and 1 (white)
color with specified red, green and blue components, each between 0 and 1
color with hue h between 0 and 1
color with specified hue, saturation and brightness, each between 0 and 1
Basic Wolfram Language color specifications.
The Wolfram Language accepts the names of many colors directly as color specifications. These color names, such as Red, Gray, LightGreen, and Purple, are implemented as variables which evaluate to an RGBColor specification. The color names can be used interchangeably with color directives.
The first plot is colored with a color name, while the second one has a fine-tuned RGBColor specification:
The function Hue[h] provides a convenient way to specify a range of colors using just one parameter. As h varies from 0 to 1, Hue[h] runs through red, yellow, green, cyan, blue, magenta, and back to red again. Hue[h,s,b] allows you to specify not only the "hue", but also the "saturation" and "brightness" of a color. Taking the saturation to be equal to one gives the deepest colors; decreasing the saturation toward zero leads to progressively more "washed out" colors.
When you give a graphics directive such as RGBColor, it affects all subsequent graphical elements that appear in a particular list. The Wolfram Language also supports various graphics directives which affect only specific types of graphical elements.
The graphics directive PointSize[d] specifies that all Point elements which appear in a graphics object should be drawn as circles with diameter d. In PointSize, the diameter d is measured as a fraction of the width of your whole plot.
The Wolfram Language also provides the graphics directive AbsolutePointSize[d], which allows you to specify the "absolute" diameter of points, measured in fixed units. The units are of an inch, approximately printer's points.
give all points a diameter d as a fraction of the width of the whole plot
give all points a diameter d measured in absolute units
Graphics directives for points.
Here is a list of points:
This makes each point have a diameter equal to onetenth of the width of the plot:
Here each point has size 3 in absolute units:
give all lines a thickness w as a fraction of the width of the whole plot
give all lines a thickness w measured in absolute units
show all lines as a sequence of dashed segments, with lengths w1 , w2 ,
use absolute units to measure dashed segments
give all lines endcaps of the specified type
give all lines joins of the specified type
Graphics directives for lines.
This generates a list of lines with different absolute thicknesses:
Here is a picture of the lines:
The Dashing graphics directive allows you to create lines with various kinds of dashing. The basic idea is to break lines into segments which are alternately drawn and omitted. By changing the lengths of the segments, you can get different line styles. Dashing allows you to specify a sequence of segment lengths. This sequence is repeated as many times as necessary in drawing the whole line.
This gives a dashed line with a succession of equallength segments:
This gives a dotdashed line:
Dashing can be turned off by specifying an empty list. Here, Dashing is turned off for only the second line:
Graphics directives which require a numerical size specification can also accept values of Tiny, Small, Medium, and Large. For each directive, these values have been fine-tuned to produce an appearance which will seem appropriate to the human eye.
This specifies a large thickness with medium dashing:
This specifies that the entire multipoint should use large, green points:
The CapForm directive lets you specify the shapes of the end caps of lines. End cap shapes can be "Butt", "Square", or "Round".
This shows the different shapes available to CapForm:
CapForm["Butt"] specifies that lines end exactly at their endpoints. "Square" end caps extend one-half line width beyond the ends of a line. "Round" end caps are half-circles whose diameter is the width of the line.
You can also specify the shapes of the joins between line segments via the JoinForm directive.
Here are the shapes available to JoinForm:
extend the join by at most d times the line width
Specifying the maximum length of miter joins.
When the angle between adjacent line segments is small, the point at a miter join can be very long. Excessively long points are by default truncated to bevel joins. The length at which this happens, the "miter limit", is by default set so that the points of 5-pointed stars are sharp, but more acute joins are beveled. You can specify an explicit miter limit using JoinForm to control exactly when sharp joins are beveled. The miter limit is the number of line widths that the point at a join is allowed to extend past the vertex of the join before it is beveled.
The points on this 7-pointed star are blunted by the default miter limit:
Specifying an explicit larger miter limit gives a pointed star:
specify that corners should be rounded with radius r
The RoundingRadius option to Rectangle.
The corners of Rectangle primitives can be rounded with the RoundingRadius option, which specifies the radius of the rectangle's corners. The actual rounding is limited to the half-length of an adjacent side.
Here are rectangles with various amounts of corner rounding:
One way to use Wolfram Language graphics directives is to insert them directly into the lists of graphics primitives used by graphics objects. Sometimes, however, you want the graphics directives to be applied more globally, and for example to determine the overall "style" with which a particular type of graphical element should be rendered. There are typically graphics options which can be set to specify such styles in terms of lists of graphics directives.
specify a style to be used for all curves in Plot
specify styles to be used (cyclically) for a sequence of curves in Plot
specify a style to be used for a mesh in density and surface graphics
specify a style to be used for the bounding box in threedimensional graphics
Some graphics options for specifying styles.
This generates a plot in which all curves are specified to use the same style:
A different PlotStyle expression can be used to give specific styles to each curve:
The various "style options" allow you to specify how particular graphical elements in a plot should be rendered. The Wolfram Language also provides options that affect the rendering of the whole plot.
specify the background color for a plot
specify the base style for a plot, affecting elements not affected by PlotStyle
give graphics to render before a plot is started
give graphics to render after a plot is finished
Graphics options that affect whole plots.
This draws the plot in white on a gray background:
This makes the epilog white as well:
Coordinate Systems for TwoDimensional Graphics
When you set up a graphics object in the Wolfram Language, you give coordinates for the various graphical elements that appear. When the Wolfram Language renders the graphics object, it has to translate the original coordinates you gave into "display coordinates" that specify where each element should be placed in the final display area.
the range of original coordinates to include in the plot
Option that determines translation from original to display coordinates.
When the Wolfram Language renders a graphics object, one of the first things it has to do is to work out what range of original and coordinates it should actually display. Any graphical elements that are outside this range will be clipped, and not shown.
The option PlotRange specifies the range of original coordinates to include. As discussed in "Options for Graphics", the default setting is PlotRange->Automatic, which makes the Wolfram Language try to choose a range which includes all "interesting" parts of a plot, while dropping "outliers". By setting PlotRange->All, you can tell the Wolfram Language to include everything. You can also give explicit ranges of coordinates to include.
This sets up a polygonal object whose corners have coordinates between roughly :
In this case, the polygonal object fills almost the whole display area:
Specifying an explicit PlotRange allows you to zoom in on a section of a graphic:
make the ratio of height to width for the display area equal to r
determine the shape of the display area from the original coordinate system
Specifying the shape of the display area.
What we have discussed so far is how the Wolfram Language translates the original coordinates you specify into positions in the final display area. What remains to discuss, however, is what the final display area is like.
On most computer systems, there is a certain fixed region of screen or paper into which the Wolfram Language display area must fit. How it fits into this region is determined by its "shape" or aspect ratio. In general, the option AspectRatio specifies the ratio of height to width for the final display area.
It is important to note that the setting of AspectRatio does not affect the meaning of the scaled or display coordinates. These coordinates always run from 0 to 1 across the display area. What AspectRatio does is to change the shape of this display area.
For twodimensional graphics, AspectRatio is set by default to Automatic. This determines the aspect ratio from the original coordinate system used in the plot instead of setting it at a fixed value. One unit in the direction in the original coordinate system corresponds to the same distance in the final display as one unit in the direction. In this way, objects that you define in the original coordinate system are displayed with their "natural shape".
This generates a graphic object corresponding to a regular hexagon. With the default value of AspectRatio->Automatic, the aspect ratio of the final display area is determined from the original coordinate system, and the hexagon is shown with its "natural shape":
This renders the hexagon in a display area whose height is three times its width:
Sometimes, you may find it convenient to specify the display coordinates for a graphical element directly. You can do this by using scaled coordinates Scaled[{sx,sy}] rather than {x,y}. The scaled coordinates are defined to run from 0 to 1 in and , with the origin taken to be at the lowerleft corner of the plot range.
original coordinates
coordinates scaled to the plot range
coordinates scaled to the display area
Coordinate systems for twodimensional graphics.
The display area is significantly larger than the plot range due to the frame label:
Using Scaled coordinates, the rectangle falls at the origin, which is at the center of the specified plot range:
Using ImageScaled coordinates, the rectangle falls at exactly the center of the graphic, which does not coincide with the center of the plot range:
When you use {x,y}, Scaled[{sx,sy}], or ImageScaled[{sx,sy}], you are specifying the position either completely in original coordinates, or completely in scaled coordinates. Sometimes, however, you may need to use a combination of these coordinate systems. For example, if you want to draw a line at a particular point whose length is a definite fraction of the width of the plot, you will have to use original coordinates to specify the basic position of the line, and scaled coordinates to specify its length.
You can use Scaled[{dsx,dsy},{x,y}] to specify a position using a mixture of original and scaled coordinates. In this case, {x,y} gives a position in original coordinates, and {dsx,dsy} gives the offset from the position in scaled coordinates.
a circle whose radius is scaled to the width of the plot range
a disk whose radius is scaled to the width of the plot range
specification for a font size scaled to the width of the plot range
Some places where Scaled can be used with a single argument.
Both the radius of the circle and the size of the font are specified in Scaled values:
scaled offset from original coordinates
image scaled offset from original coordinates
absolute offset from original coordinates
absolute offset from scaled coordinates
absolute offset from image scaled coordinates
Positions specified as offsets.
Each line drawn here has an absolute length of six printer's points:
You can also use Offset inside Circle with just one argument to create a circle with a certain absolute radius:
In most kinds of graphics, you typically want the relative positions of different objects to adjust automatically when you change the coordinates or the overall size of your plot. But sometimes you may instead want the offset from one object to another to be constrained to remain fixed. This can be the case, for example, when you are making a collection of plots in which you want certain features to remain consistent, even though the different plots have different forms.
Offset[{adx,ady},position] allows you to specify the position of an object by giving an absolute offset from a position that is specified in original or scaled coordinates. The units for the offset are printer's points, equal to of an inch.
When you give text in a plot, the size of the font that is used is also specified in printer's points. Therefore, a 10point font, for example, has letters whose basic height is 10 printer's points. You can use Offset to move text around in a plot, and to create plotting symbols or icons which match the size of the text.
Using scaled coordinates, you can specify the sizes of graphical elements as fractions of the size of the display area. You cannot, however, tell the Wolfram Language the actual physical size at which a particular graphical element should be rendered. Of course, this size ultimately depends on the details of your graphics output device, and cannot be determined for certain within the Wolfram Language. Nevertheless, graphics directives such as AbsoluteThickness discussed in "Graphics Directives and Options" do allow you to indicate "absolute sizes" to use for particular graphical elements. The sizes you request in this way will be respected by most, but not all, output devices. (For example, if you optically project an image, it is neither possible nor desirable to maintain the same absolute size for a graphical element within it.)
Labeling TwoDimensional Graphics
give a pair of axes
draw grid lines on the plot
put axes on a frame around the plot
give an overall label for the plot
Ways to label twodimensional plots.
Here is a plot, using the default Axes->True:
Setting Frame->True generates a frame with axes, and removes tick marks from the ordinary axes:
This includes grid lines, which are shown in light gray:
draw no axes
draw both and axes
draw a axis but no axis
choose the crossing point for the axes automatically
specify the crossing point
specify the style for the axes
specify individual styles for the axes
give no axis labels
put a label on the axis
put labels on both the and axes
Options for axes.
This makes the axes cross at the point {5,0}, and puts a label on each axis:
draw no tick marks
place tick marks automatically
specify tick marks for each axis
Settings for the Ticks option.
With the default setting Ticks->Automatic, the Wolfram Language creates a certain number of major and minor tick marks, and places them on axes at positions which yield the minimum number of decimal digits in the tick labels. In some cases, however, you may want to specify the positions and properties of tick marks explicitly. You will need to do this, for example, if you want to have tick marks at multiples of , or if you want to put a nonlinear scale on an axis.
draw no tick marks
place tick marks automatically
draw tick marks at the specified positions
draw tick marks with the specified labels
draw tick marks with the specified scaled lengths
draw tick marks with the specified lengths in the positive and negative directions
draw tick marks with the specified styles
a function to be applied to xmin, xmax to get the tick mark option
Tick mark options for each axis.
This gives tick marks at specified positions on the axis, and chooses the tick marks automatically on the axis:
This adds tick marks with no labels at multiples of :
Particularly when you want to create complicated tick mark specifications, it is often convenient to define a "tick mark function" which creates the appropriate tick mark specification given the minimum and maximum values on a particular axis.
This defines a function which gives a list of tick mark positions with a spacing of 1:
This uses the units function to specify tick marks for the axis:
draw no frame
draw a frame around the plot
specify a style for the frame
specify styles for each edge of the frame
give no frame labels
put labels on edges of the frame
do not rotate text in labels
draw no tick marks on frame edges
position tick marks automatically
specify tick marks for frame edges
Options for frame axes.
The Axes option allows you to draw a single pair of axes in a plot. Sometimes, however, you may instead want to show the scales for a plot on a frame, typically drawn around the whole plot. The option Frame allows you effectively to draw four axes, corresponding to the four edges of the frame around a plot.
This draws frame axes, and labels each of them:
draw no grid lines
position grid lines automatically
specify grid lines in analogy with tick marks
Options for grid lines.
Grid lines in the Wolfram Language work very much like tick marks. As with tick marks, you can specify explicit positions for grid lines. There is no label or length to specify for grid lines. However, you can specify a style.
This generates but not grid lines:
Insetting Objects in Graphics
"Redrawing and Combining Plots" describes how you can make regular arrays of plots using GraphicsGrid. Using the Inset graphics primitive, however, you can combine and superimpose plots in any way.
Inset[obj, pos]
specifies that the inset should be placed at position pos in the graphic
Inset[obj,pos, opos, size]
render an object with a given size so that point opos in obj is positioned at point pos in the containing graphic
Inset[obj,pos, opos, size, dirs]
specifies that the axes of the inset should be oriented in directions dirs
Creating an inset.
Here is a plot:
This creates a plot within a parametric plot:
Here is a threedimensional plot:
This creates a twodimensional graphics object that contains two differently sized copies of the threedimensional plot:
Here are rotated and skewed plots inset in a graphic:
The Wolfram Language can render plots, arbitrary 2D or 3D graphics, cells, and text within an Inset. Notice that in general the display area for graphics objects will be sized so as to touch at least one pair of edges of the Inset.
Density and Contour Plots
make a density plot of f
make a contour plot of f as a function of x and y
Density and contour plots.
This gives a density plot of . Lighter regions show higher values of the function:
option name
default value
what colors to use for shading; Hue uses a sequence of hues
whether to draw a mesh
number of initial sample points in each direction
the maximum number of recursive subdivision steps to do
Some options for DensityPlot.
You can include a mesh like this:
In a density plot, the color of each point represents the value at that point of the function being plotted. By default, the color ranges from black to white through intermediate shades of blue as the value of the function increases. In general, however, you can specify other "color maps" for the relation between the value at a point and its color. The option ColorFunction allows you to specify a function which is applied to the function value to find the color at any point. The color function may return any Wolfram Language color directive, such as GrayLevel, Hue, or RGBColor. A common setting to use is ColorFunction->Hue.
This uses different hues to represent different values:
A significant resource for customized color functions is the ColorData function. ColorData provides many customized sets of colors which can be used directly by ColorFunction.
This shows a list of the gradients which can be accessed using ColorData:
This DensityPlot is identical to the one above, but uses the "SolarColors" gradient:
This gives a contour plot of the function:
A contour plot gives you essentially a "topographic map" of a function. The contours join points on the surface that have the same height. The default is to have contours corresponding to a sequence of equally spaced z values. Contour plots produced by the Wolfram Language are by default shaded, in such a way that regions with higher z values are lighter.
option name
default value
what colors to use for shading; Hue uses a sequence of hues
the total number of contours, or the list of z values for contours
the range of values to be included; you can specify {zmin,zmax}, All or Automatic, or a list {xrange,yrange,zrange}
how to shade the regions; None leaves the regions blank, or a list of colors can be provided
number of initial sample points in each direction
the maximum number of recursive subdivision steps to do
Some options for ContourPlot.
This shows the plot with no shading:
This cycles the colors used for contour regions between light red and light purple:
Both DensityPlot and ContourPlot use an adaptive algorithm that subdivides parts of the plot region to obtain more sample points for a smoother representation of the function you are plotting. Because the number of sample points is always finite, however, it is possible that features of your function will sometimes be missed. When necessary, you can increase the number of sample points by increasing the values of the PlotPoints and MaxRecursion options.
One point to notice is that whereas a curve generated by Plot may be inaccurate if your function varies too quickly in a particular region, the shape of contours generated by ContourPlot can be inaccurate if your function varies too slowly. A rapidly varying function gives a regular pattern of contours, but a function that is almost flat can give irregular contours. You can typically overcome this by increasing the value of PlotPoints or MaxRecursion.
ThreeDimensional Graphics Primitives
One of the most powerful aspects of graphics in the Wolfram System is the availability of threedimensional as well as twodimensional graphics primitives. By combining threedimensional graphics primitives, you can represent and render threedimensional objects in the Wolfram System.
point with coordinates x, y, z
line through the points {x1,y1,z1}, {x2,y2,z2},
filled polygon with the specified list of corners
arrow pointing from pt1 to pt2
text at position {x,y,z} (see "Graphics Primitives for Text")
Threedimensional graphics elements.
Every time you evaluate rcoord, it generates a random coordinate in three dimensions:
This generates a list of 20 random points in threedimensional space:
Here is a plot of the points:
This gives a plot showing a line through 10 random points in three dimensions:
If you give a list of graphics elements in two dimensions, the Wolfram System simply draws each element in turn, with later elements obscuring earlier ones. In three dimensions, however, the Wolfram System collects together all the graphics elements you specify, then displays them as threedimensional objects, with the ones in front in threedimensional space obscuring those behind.
Every time you evaluate rantri, it generates a random triangle in threedimensional space:
This draws a single random triangle:
This draws a collection of 5 random triangles. The triangles in front obscure those behind:
By creating an appropriate list of polygons, you can build up any threedimensional object in the Wolfram System. Thus, for example, all the surfaces produced by ParametricPlot3D are represented essentially as lists of polygons.
a multipoint consisting of points at pt1, pt2,
a multiline consisting of lines line1, line2,
a multipolygon consisting of polygons poly1, poly2,
Primitives which can take multiple elements.
As with the two-dimensional primitives, some three-dimensional graphics primitives have multi-coordinate forms, which are a more efficient representation. When dealing with a very large number of primitives, using these multi-coordinate forms where possible can both reduce the memory footprint of the resulting graphic and make it render much more quickly.
rantricoords defines merely the coordinates of a random triangle:
Using the multi-coordinate form of Polygon, this efficiently represents a very large number of triangles:
The Wolfram System allows polygons in three dimensions to have any number of vertices in any configuration. Depending upon the locations of the vertices, the resulting polygons may be non-coplanar or nonconvex. When rendering non-coplanar polygons, the Wolfram System will break the polygon into triangles, which are planar by definition, before rendering it.
The non-coplanar polygon is broken up into triangles. The interior edge joining the triangles is not outlined like the outer edges of the Polygon primitive:
Self-intersecting nonconvex polygons are filled according to an evenodd rule that alternates between filling and not filling at each crossing:
a cone with a base radius of 1 centered around {x1,y1,z1} with the point at {x2,y2,z2}
a cone with a base radius of r
a unit cube with opposite corners having coordinates {x,y,z} and {x+1,y+1,z+1}
a cuboid (rectangular parallelepiped) with opposite corners having the specified coordinates
a cylinder of radius 1 with endpoints at {x1,y1,z1} and {x2,y2,z2}
a cylinder of radius r
a unit sphere centered at {x,y,z}
a sphere of radius r
a tube connecting the specified points
a tube of radius r
Cuboid graphics elements.
This draws a number of random unit cubes and spheres in threedimensional space:
Even though Cone, Cylinder, Sphere, and Tube produce high-quality renderings, their usage is scalable. A single image can contain thousands of these primitives. When rendering so many primitives, you can increase the efficiency of rendering by using special options to change the number of points used by default to render Cone, Cylinder, Sphere, and Tube. The "ConePoints" Method option to Graphics3D is used to reduce the rendering quality of each individual cone. Cylinder, sphere, and tube quality can be similarly adjusted using "CylinderPoints", "SpherePoints", and "TubePoints", respectively.
Because the cylinders are so small, the number of points used to render them can be reduced with almost no perceptible change:
ThreeDimensional Graphics Directives
In three dimensions, just as in two dimensions, you can give various graphics directives to specify how the different elements in a graphics object should be rendered.
All the graphics directives for two dimensions also work in three dimensions. There are, however, some additional directives in three dimensions.
Just as in two dimensions, you can use the directives PointSize, Thickness, and Dashing to tell the Wolfram System how to render Point and Line elements. Note that in three dimensions, the lengths that appear in these directives are measured as fractions of the total width of the display area for your plot.
This generates a list of 20 random points in three dimensions:
This displays the points, with each one being a circle whose diameter is 5% of the display area width:
As in two dimensions, you can use AbsolutePointSize, AbsoluteThickness, and AbsoluteDashing if you want to measure length in absolute units.
This generates a line through 10 random points in three dimensions:
This shows the line dashed, with a thickness of two printer's points:
For Point and Line objects, the color specification directives also work the same in three dimensions as in two dimensions. For Polygon objects, however, they can work differently.
In two dimensions, polygons are always assumed to have an intrinsic color, specified directly by graphics directives such as RGBColor and Opacity. In three dimensions, however, the Wolfram System generates colors for polygons using a more physical approach based on simulated illumination. Polygons continue to have an intrinsic color defined by color directives, but the final color observed when rendering the graphic may be different based upon the values of the lights shining on the polygon. Polygons are intrinsically white by default.
use default light placements and values
disable all lights
light using only white light sources
Some schemes for coloring polygons in three dimensions.
This draws an icosahedron with default lighting. The intrinsic color value of the polygons is white:
This draws the icosahedron using the same lighting parameters, but defines the intrinsic color value of the polygons to be gray:
The intrinsic color value of the polygons becomes more obvious when using the "Neutral" lighting scheme:
This applies the gray color only to the line, which is not affected by the lights:
As with two-dimensional directives, the color directive can be scoped to the line by using a sublist:
draw no lines at the edges of polygons
use the graphics directives g to determine how to draw lines at the edges of polygons
Giving graphics directives for all the edges of polygons.
When you render a threedimensional graphics object in the Wolfram System, there are two kinds of lines that can appear. The first kind is lines from explicit Line primitives that you included in the graphics object. The second kind is lines that were generated as the edges of polygons.
You can tell the Wolfram System how to render all lines of the second kind by giving a list of graphics directives inside EdgeForm.
This renders a dodecahedron with its edges shown as thick gray lines:
use gfront graphics directives for the front face of each polygon, and gback for the back
Rendering the fronts and backs of polygons differently.
An important aspect of polygons in three dimensions is that they have both front and back faces. The Wolfram System uses the following convention to define the "front face" of a polygon: if you look at a polygon from the front, then the corners of the polygon will appear counterclockwise, when taken in the order that you specified them.
This makes the front (outside) face of each polygon mostly transparent, and the back (inside) face fully opaque:
Coordinate Systems for ThreeDimensional Graphics
Whenever the Wolfram Language draws a threedimensional object, it always effectively puts a cuboidal box around the object. With the default option setting Boxed->True, the Wolfram Language in fact draws the edges of this box explicitly. But in general, the Wolfram Language automatically "clips" any parts of your object that extend outside of the cuboidal box.
The option PlotRange specifies the range of , , and coordinates that the Wolfram Language should include in the box. As in two dimensions the default setting is PlotRange->Automatic, which makes the Wolfram Language use an internal algorithm to try and include the "interesting parts" of a plot, but drop outlying parts. With PlotRange->All, the Wolfram Language will include all parts.
This loads a package defining polyhedron operations:
This creates a stellated icosahedron:
This shows the stellated icosahedron, drawn in a box:
With this setting for PlotRange, many parts of the stellated icosahedron lie outside the box, and are clipped:
Much as in two dimensions, you can use either "original" or "scaled" coordinates to specify the positions of elements in threedimensional objects. Scaled coordinates, specified as Scaled[{sx,sy,sz}], are taken to run from 0 to 1 in each dimension. The coordinates are set up to define a righthanded coordinate system on the box.
original coordinates
scaled coordinates, running from 0 to 1 in each dimension
Coordinate systems for threedimensional objects.
This puts a cuboid in one corner of the box:
Once you have specified where various graphical elements go inside a threedimensional box, you must then tell the Wolfram Language how to draw the box. The first step is to specify what shape the box should be. This is analogous to specifying the aspect ratio of a twodimensional plot. In three dimensions, you can use the option BoxRatios to specify the ratio of side lengths for the box. For Graphics3D objects, the default is BoxRatios->Automatic, specifying that the shape of the box should be determined from the ranges of actual coordinates for its contents.
specify the ratio of side lengths for the box
determine the ratio of side lengths from the range of actual coordinates (default for Graphics3D )
Specifying the shape of the bounding box for threedimensional objects.
This displays the stellated icosahedron in a tall box:
To produce an image of a threedimensional object, you have to tell the Wolfram Language from what view point you want to look at the object. You can do this using the option ViewPoint.
Some common settings for this option were given in "Three-Dimensional Surface Plots". In general, however, you can tell the Wolfram Language to use any view point.
View points are specified in the form ViewPoint->{sx,sy,sz}. The values si are given in a special coordinate system, in which the center of the box is {0,0,0}. The special coordinates are scaled so that the longest side of the box corresponds to one unit. The lengths of the other sides of the box in this coordinate system are determined by the setting for the BoxRatios option. For a cubical box, therefore, each of the special coordinates runs from to across the box. Note that the view point must always lie outside the box.
This generates a picture using the default view point {1.3,-2.4,2}:
This is what you get with a view point close to one of the corners of the box:
As you move away from the box, the perspective effect gets smaller:
option name
default value
the point in a special scaled coordinate system from which to view the object
the point in the scaled coordinate system that appears at the center of the final image
the direction in the scaled coordinate system that appears as vertical in the final image
the opening angle for a simulated camera used to view the graphic
the position and direction of the simulated camera in the graphic's regular coordinate system
Specifying the position and orientation of threedimensional objects.
In making a picture of a threedimensional object, you have to specify more than just where you want to look at the object from. You also have to specify how you want to "frame" the object in your final image. You can do this using the additional options ViewCenter, ViewVertical, and ViewAngle.
ViewCenter allows you to tell the Wolfram Language what point in the object should appear at the center of your final image. The point is specified by giving its scaled coordinates, running from 0 to 1 in each direction across the box. With the setting ViewCenter->{1/2,1/2,1/2}, the center of the box will therefore appear at the center of your final image. With many choices of view point, however, the box will not appear symmetrical, so this setting for ViewCenter will not center the whole box in the final image area. You can do this by setting ViewCenter->Automatic.
ViewVertical specifies which way up the object should appear in your final image. The setting for ViewVertical gives the direction in scaled coordinates that ends up vertical in the final image. With the default setting ViewVertical->{0,0,1}, the direction in your original coordinate system always ends up vertical in the final image.
The Wolfram Language uses the properties of a simulated camera to visualize the final image. The position, orientation, and facing of the camera are determined by the ViewCenter, ViewVertical, and ViewPoint options. The ViewAngle option specifies the width of the opening of the camera lens. The ViewAngle specifies, in radians, twice of the maximum angle from the line stretching from the ViewPoint to the ViewCenter that can be viewed by the camera. This means that ViewAngle can effectively be used to zoom in on a part of the image. The default value of ViewAngle resolves to 35°, which is the typical viewing angle for the human eye.
This setting for ViewVertical makes the axis of the box appear vertical in your image:
This uses ViewAngle to effectively zoom in on the center of the image:
When you set the options ViewPoint, ViewCenter, and ViewVertical, you can think about it as specifying how you would look at a physical object. ViewPoint specifies where your head is relative to the object. ViewCenter specifies where you are looking (the center of your gaze). And ViewVertical specifies which way up your head is.
In terms of coordinate systems, settings for ViewPoint, ViewCenter, and ViewVertical specify how coordinates in the threedimensional box should be transformed into coordinates for your image in the final display area.
uses the values of the ViewPoint and ViewCenter options to determine the position and facing of the simulated camera
position of the camera in the coordinates used for objects; the facing of the camera is determined by the ViewCenter option
position of the camera and of the point the camera is focused on in the coordinates used for objects
Possible values of the ViewVector option.
The position and facing of the camera can be fully determined by the ViewPoint and ViewCenter options, but the ViewVector option offers a useful generalization. Instead of specifying the position and facing of the camera using scaled coordinates, ViewVector provides the ability to position the camera using the same coordinate system used to position objects within the graphic.
This specifies that the camera should be placed on the negative axis and facing toward the center of the graphic:
The camera is in the same position but pointing in a different direction. In combination with ViewAngle, this zooms in on a particular section of the graphic:
Once you have obtained a twodimensional image of a threedimensional object, there are still some issues about how this image should be rendered. The issues, however, are identical to those that occur for twodimensional graphics. Thus, for example, you can modify the final shape of your image by changing the AspectRatio option. And you specify what region of your whole display area your image should take up by setting the PlotRegion option.
rotate the graphic about its center
Ctrl + drag
zoom into or out of the graphic
Shift + drag
pan across the graphic in the plane of the screen
Mouse gestures used for interacting with three-dimensional graphics.
When interactively modifying graphics, the Wolfram Language makes changes to the view options. If you have specified the position of the camera using ViewPoint, then rotating the graphic causes the Wolfram Language to change the value of the ViewPoint option. If the position of the camera is specified using ViewVector, interactive rotation will instead change the value of that option. In both cases, interactive rotation can also affect the value of the ViewVertical option. Interactive zooming of the graphic corresponds directly to changing the ViewAngle option. Interactively panning the graphic changes values of the ViewCenter option.
This modifies the aspect ratio of the final image:
The Wolfram Language usually scales the images of threedimensional objects to be as large as possible, given the display area you specify. Although in most cases this scaling is what you want, it does have the consequence that the size at which a particular threedimensional object is drawn may vary with the orientation of the object. You can set the option SphericalRegion->True to avoid such variation. With this option setting, the Wolfram Language effectively puts a sphere around the threedimensional bounding box, and scales the final image so that the whole of this sphere fits inside the display area you specify. The sphere has its center at the center of the bounding box, and is drawn so that the bounding box just fits inside it.
This draws a rather elongated version of the plot:
With SphericalRegion->True, the final image is scaled so that a sphere placed around the bounding box would fit in the display area:
By setting SphericalRegion->True, you can make the scaling of an object consistent for all orientations of the object. This is useful if you create animated sequences that show a particular object in several different orientations.
scale threedimensional images to be as large as possible
scale images so that a sphere drawn around the threedimensional bounding box would fit in the final display area
Changing the magnification of threedimensional images.
Lighting and Surface Properties
With the default option setting Lighting->Automatic, the Wolfram Language uses a simulated lighting model to determine how to color polygons in threedimensional graphics.
The Wolfram Language allows you to specify various components to the illumination of an object. One component is the "ambient lighting", which produces uniform shading all over the object. Other components are directional, and produce different shading on different parts of the object. "Point lighting" simulates light emanating in all directions from one point in space. "Spot lighting" is similar to point lighting, but emanates a cone of light in a particular direction. "Directional lighting" simulates a uniform field of light pointing in the given direction. The Wolfram Language adds together the light from all of these sources in determining the total illumination of a particular polygon.
uniform ambient lighting
directional lighting parallel to the vector from pos1 to pos2
spherical point light source at position pos
spotlight at position pos aimed at the target position tar with a half-angle opening of α
a number of lights
Methods for specifying light sources.
The default lighting used by the Wolfram Language involves three point light sources, and no ambient component. The light sources are colored respectively red, green and blue, and are placed at angles on the righthand side of the object.
Here is a sphere, shaded using simulated lighting using the default set of lights:
This shows the result of adding ambient light, and removing all point light sources. Note the Lighting option takes a list of light sources:
This adds a single point light source positioned at the red point. The lights are combined as appropriate:
Objects do not block light sources or cast shadows, so all objects in a scene will be lit evenly by light sources:
This adds a directional green light shining from the negative direction, effectively an infinite distance away:
This shows a spotlight positioned above the plot, combined with ambient lighting:
The Lighting option controls the lighting of all objects in a scene when used as an option to Graphics3D or Show. Lighting can also be used inline as a directive which specifies lighting for particular objects. The Lighting directive replaces the inherited lighting specifications.
The Lighting directive replaces the default value of Lighting for the two spheres after the directive:
This example uses list braces to restrict the effect of the Lighting directive to the middle sphere:
The perceived color of a polygon depends not only on the light which falls on the polygon, but also on how the polygon reflects that light. You can use the graphics directives RGBColor, Specularity, and Glow to specify the way that polygons reflect or emit light.
If you do not explicitly use these coloring directives, the Wolfram Language effectively assumes that all polygons have matte white surfaces. Thus the polygons reflect light of any color incident on them, and do so equally in all directions. This is an appropriate model for materials such as uncoated white paper.
Using RGBColor, Specularity, and Glow, however, you can specify more complicated models. These directives separately specify three kinds of light emission: diffuse reflection, specular reflection, and glow.
In diffuse reflection, light incident on a surface is scattered equally in all directions. When this kind of reflection occurs, a surface has a "dull" or "matte" appearance. Diffuse reflectors obey Lambert's law of light reflection, which states that the intensity of reflected light is times the intensity of the incident light, where is the angle between the incident light direction and the surface normal vector. Note that when , there is no reflected light.
In specular reflection, a surface reflects light in a mirrorlike way. As a result, the surface has a "shiny" or "gloss" appearance. With a perfect mirror, light incident at a particular angle is reflected at exactly the same angle. Most materials, however, scatter light to some extent, and so lead to reflected light that is distributed over a range of angles. The Wolfram Language allows you to specify how broad the distribution is by giving a specular exponent, defined according to the Phong lighting model. With specular exponent , the intensity of light at an angle away from the mirror reflection direction is assumed to vary like . As , therefore, the surface behaves like a perfect mirror. As decreases, however, the surface becomes less "shiny", and for , the surface is a completely diffuse reflector. Typical values of for actual materials range from about 1 to several hundred.
Glow is light radiated from a surface at a certain color and intensity of light that is independent of incident light.
Most actual materials show a mixture of diffuse and specular reflection, and some objects glow in addition to reflecting light. For each kind of light emission, an object can have an intrinsic color. For diffuse reflection, when the incident light is white, the color of the reflected light is the material's intrinsic color. When the incident light is not white, each color component in the reflected light is a product of the corresponding component in the incident light and in the intrinsic color of the material. Similarly, an object may have an intrinsic specular reflection color, which may be different from its diffuse reflection color, and the specularly reflected light is a componentwise product of the incident light and the intrinsic specular color. For glow, the color emitted is determined by intrinsic properties alone, with no dependence on incident light.
In the Wolfram Language, you can specify light properties by giving any combination of diffuse reflection, specular reflection, and glow directives. To get no reflection of a particular kind, you may give the corresponding intrinsic color as Black, or GrayLevel[0]. For materials that are effectively "white", you can specify intrinsic colors of the form GrayLevel[a], where a is the reflectance or albedo of the surface.
matte surface with albedo a
matte surface with intrinsic color
surface with specularity spec and specular exponent n; spec can be a number between 0 and 1 or an RGBColor specification
glowing surface with color col
Specifying surface properties of lighted objects.
This shows a sphere with the default matte white surface, illuminated by several colored light sources:
This makes the sphere have low diffuse reflectance, but high specular reflectance. As a result, the sphere has a "specular highlight" near the light sources, and is quite dark elsewhere:
When you set up light sources and surface colors, it is important to make sure that the total intensity of light reflected from a particular polygon is never larger than 1. You will get strange effects if the intensity is larger than 1.
Labeling ThreeDimensional Graphics
The Wolfram Language provides various options for labeling threedimensional graphics. Some of these options are directly analogous to those for twodimensional graphics, discussed in "Labeling Two-Dimensional Graphics". Others are different.
draw a cuboidal bounding box around the graphics (default)
draw , , and axes on the edges of the box
draw the axis only
draw grid lines on the faces of the box
give an overall label for the plot
Some options for labeling threedimensional graphics.
The default for Graphics3D is to include a box, but no other forms of labeling:
Setting Axes->True adds , , and axes:
This adds grid lines to each face of the box:
specify the style for the box
specify the style for the axes
specify separate styles for each axis
Style options.
This makes the box dashed, and draws axes that are thicker than normal:
By setting the option Axes->True, you tell the Wolfram Language to draw axes on the edges of the threedimensional box. However, for each axis, there are in principle four possible edges on which it can be drawn. The option AxesEdge allows you to specify on which edge to draw each of the axes.
use an internal algorithm to choose where to draw all axes
give separate specifications for each of the , , and axes
do not draw this axis
decide automatically where to draw this axis
specify on which of the four possible edges to draw this axis
Specifying where to draw threedimensional axes.
This draws the on the edge with larger and coordinates, draws no axis, and chooses automatically where to draw the axis:
When you draw the axis on a threedimensional box, there are four possible edges on which the axis can be drawn. These edges are distinguished by having larger or smaller and coordinates. When you use the specification for where to draw the axis, you can set the to be +1 or -1 to represent larger or smaller values for the and coordinates.
give no axis labels
put a label on the axis
put labels on all three axes
Axis labels in threedimensional graphics.
You can use AxesLabel to label edges of the box, without necessarily drawing scales on them:
draw no tick marks
place tick marks automatically
specify tick marks for each axis
Settings for the Ticks option.
You can give the same kind of tick mark specifications in three dimensions as were described for twodimensional graphics in "Labeling Two-Dimensional Graphics".
draw no grid lines on faces
draw grid lines on all faces
draw grid lines on the faces specified by the facei
use xgridi, ygridi to determine where and how to draw grid lines on each face
Drawing grid lines in three dimensions.
The Wolfram Language allows you to draw grid lines on the faces of the box that surrounds a threedimensional object. If you set FaceGrids->All, grid lines are drawn in gray on every face. By setting FaceGrids->{face1,face2,} you can tell the Wolfram Language to draw grid lines only on specific faces. Each face is specified by a list , where two of the must be 0, and the third one is +1 or -1. For each face, you can also explicitly tell the Wolfram Language where and how to draw the grid lines, using the same kind of specifications as you give for the GridLines option in twodimensional graphics.
This draws grid lines only on the top and bottom faces of the box:
Efficient Representation of Many Primitives
a multipoint consisting of points at pt1, pt2,
a multiline consisting of lines line1, line2,
a multipolygon consisting of polygons poly1, poly2,
Primitives which can take multiple elements.
Some primitives have multi-element forms that can be processed and rendered more quickly by the Wolfram System front end than the equivalent individual primitives. For large numbers of primitives, using the multi-element forms can also significantly reduce the sizes of notebook files. Notebooks that use multi-element forms can be less than half the size of those that do not, and render up to ten times faster.
Here is a multipoint random distribution:
a graphics complex in which coordinates given as integers i in graphics primitives in data are taken to be pti
Primitive for sharing coordinate data among primitives.
When many primitives share the same coordinate data, as in meshes and graphs, further efficiency can be gained by using GraphicsComplex to factor out the coordinate data. The output of the Wolfram Language's surface- and graph-plotting functions typically use this representation.
Here is a structure of points and lines that share coordinates:
In addition to being efficient, GraphicsComplex is useful interactively. Primitives that share coordinates stay connected when one of them is dragged.
Because the output of GraphPlot is a GraphicsComplex, the graph stays connected when any part of it is dragged:
Any primitive may be used within a GraphicsComplex, and GraphicsComplex can be used in both 2D and 3D graphics. Within GraphicsComplex, coordinate positions in primitives are replaced by indices into the coordinate data in the GraphicsComplex.
This GraphicsComplex combines several types of primitives:
GraphicsComplex is especially useful for representing meshes of polygons. By using GraphicsComplex, numerical errors that could cause gaps between adjacent polygons are avoided.
The output of Plot3D is a GraphicsComplex:
Formats for Text in Graphics
an option for the text style in a graphic
an option for the text format type in a graphic
Specifying formats for text in graphics.
Here is a plot with default settings for all formats:
Here is the same plot, but now using a 12point bold font:
This uses StandardForm rather than TraditionalForm:
This tells the Wolfram Language what default text style to use for all subsequent plots:
Now all the text is in 14point Times font:
a named style in your current stylesheet
the size of font to use in printers points
use an italic font
use a bold font
specify the name of the font family to use (e.g. "Times" , "Courier" , "Helvetica" )
Typical elements used in the setting for BaseStyle.
If you use the standard notebook front end for the Wolfram Language, then you can set BaseStyle to be the name of a style defined in your current notebook's stylesheet. You can also explicitly specify how text should be formatted by using options such as FontSize and FontFamily. Note that FontSize gives the absolute size of the font to use, measured in units of printers points, with one point being inches. If you resize a plot whose font size is specified as a number, the text in it will not by default change size: to get text of a different size you must explicitly specify a new value for the FontSize option. If you resize a plot whose font size is specified as a scaled quantity, the font will scale as the plot is resized. With FontSize->Scaled[s], the effective font size will be s scaled units in the plot.
Now all the text resizes as the plot is resized:
output expr in the specified style
output expr using the specified font and style options
output expr in StandardForm
Changing the formats of individual pieces of output.
This outputs the plot label using the section heading style in your current notebook:
This uses the section heading style, but modified to be in italics:
This produces StandardForm output, with a 12point font:
You should realize that the ability to refer to styles such as "Section" depends on using the standard Wolfram Language notebook front end. Even if you are just using a textbased interface to the Wolfram Language, however, you can still specify formatting of text in graphics using options such as FontSize. The complete collection of options that you can use is given in "Text and Font Options".
Graphics Primitives for Text
With the Text graphics primitive, you can insert text at any position in two or threedimensional Wolfram Language graphics. Unless you explicitly specify a style or font using Style, the text will be given in the graphic's base style.
text centered at the point {x,y}
text with its lefthand end at {x,y}
righthand end at {x,y}
centered above {x,y}
centered below {x,y}
text positioned so that {x,y} is at relative coordinates {dx,dy} within the box that bounds the text
text oriented vertically to read from bottom to top
text that reads from top to bottom
text that is upsidedown
Twodimensional text.
This generates five pieces of text, and displays them in a plot:
Here is some vertically oriented text with its lefthand side at the point {2,2}:
When you specify an offset for text, the relative coordinates that are used are taken to run from to in each direction across the box that bounds the text. The point {0,0} in this coordinate system is defined to be center of the text. Note that the offsets you specify need not lie in the range to .
Note that you can specify the color of a piece of text by preceding the Text graphics primitive with an appropriate RGBColor or other graphics directive.
text centered at the point {x,y,z}
text with a twodimensional offset
Threedimensional text.
This puts text at the specified position in three dimensions:
Note that when you use text in threedimensional graphics, the Wolfram Language assumes that the text is never hidden by any polygons or other objects.
option name
default value
background color
style or font specification
format type
Options for Text.
By default, the text is just put straight on top of whatever graphics have already been drawn:
Now there is a rectangle with the background color of the whole plot enclosing the text:
The Representation of Sound
"Sound" describes how you can take functions and lists of data and produce sounds from them. This tutorial discusses how sounds are represented in the Wolfram System.
The Wolfram System treats sounds much like graphics. In fact, the Wolfram System allows you to combine graphics with sound to create pictures with "sound tracks".
In analogy with graphics, sounds in the Wolfram System are represented by symbolic sound objects. The sound objects have head Sound, and contain a list of sound primitives, which represent sounds to be played in sequence.
a sound object containing a list of sound primitives
The structure of a sound object.
The functions Play and ListPlay discussed in "Sound" return Sound objects.
Play returns a Sound object. On appropriate computer systems, it also produces sound:

Sound Primitives

a sound with a sequence of amplitude levels, sampled at rate r
a sound whose amplitude levels sampled at rate r are found by applying the function f to n successive integers
a note-like sound with note n, time specification t, with the specified style
Wolfram System sound primitives.
At the lowest level, all sounds in the Wolfram System are represented as a sequence of amplitude samples, or as a sequence of MIDI events. In SampledSoundList, these amplitude samples are given explicitly in a list. In SampledSoundFunction, however, they are generated when the sound is output, by applying the specified function to a sequence of integer arguments. In both cases, all amplitude values obtained must be between and . In SoundNote, a note-like sound is represented as a sequence of MIDI events that represent the frequency, duration, amplitude, and styling of the note.
Create a SampledSoundList from a numeric list, with a sample rate of 8000:
Create a SampledSoundFunction from a function, with a sample rate of 8000:
Create a SoundNote:
ListPlay generates SampledSoundList primitives, while Play generates SampledSoundFunction primitives. With the default option setting Compiled->True, Play will produce a SampledSoundFunction object containing a CompiledFunction.
Once you have generated a Sound object containing various sound primitives, you must then output it as a sound. Much as with graphics, the basic scheme is to take the Wolfram System representation of the sound and convert it to a lowerlevel form that can be handled by an external program, such as a Wolfram System front end.
Play multiple primitives successively:
Play multiple primitives overlapped:
The lowlevel representation of sampled sound used by the Wolfram System consists of a sequence of hexadecimal numbers specifying amplitude levels. Within the Wolfram System, amplitude levels are given as approximate real numbers between and . In producing the lowlevel form, the amplitude levels are "quantized". You can use the option SampleDepth to specify how many bits should be used for each sample. The default is SampleDepth->8, which yields 256 possible amplitude levels, sufficient for most purposes. The low-level representation of note-based sound is as a time-quantized byte stream of MIDI events that specify various parameters about the note objects. The quantization of time is determined automatically at playback.
You can use the option SampleDepth in Play and ListPlay. In sound primitives, you can specify the sample depth by replacing the sample rate argument by the list {rate,depth}.


import a sound
export a sound
Importing and exporting functions.
It is possible to import audio data from a file on the local file system or from any accessible remote location.
This imports a sound from the Wolfram Language documentation directory:
Use Export to write a sound to disk.
Write the imported Sound to disk:
Exporting Graphics and Sounds
The Wolfram Language allows you to export graphics and sounds in a wide variety of formats. If you use the notebook front end for the Wolfram Language, then you can typically just copy and paste graphics and sounds directly into other programs using the standard mechanism available on your computer system.
export graphics to a file in a format deduced from the file name
export graphics in the specified format
export graphics to an external command
export a sequence of graphics for an animation
generate a string representation of exported graphics
Exporting Wolfram Language graphics and sounds.
Encapsulated PostScript ( .eps )
Adobe Acrobat portable document format ( .pdf )
Scalable Vector Graphics ( .svg )
Macintosh PICT
Windows metafile format ( .wmf )
TIFF ( .tif , .tiff )
GIF and animated GIF ( .gif )
JPEG ( .jpg , .jpeg )
PNG format ( .png )
Microsoft bitmap format ( .bmp )
PCX format ( .pcx )
X window system bitmap ( .xbm )
portable bitmap format ( .pbm )
portable pixmap format ( .ppm )
portable graymap format ( .pgm )
portable anymap format ( .pnm )
DICOM medical imaging format ( .dcm , .dic )
Audio Video Interleave format ( .avi )
Typical graphics formats supported by the Wolfram Language. Formats in the first group are resolution independent.
This generates a plot:
This exports the plot to a file in Encapsulated PostScript format:
When you export a graphic outside of the Wolfram Language, you usually have to specify the absolute size at which the graphic should be rendered. You can do this using the ImageSize option to Export.
ImageSize->x makes the width of the graphic be x printer's points; ImageSize->72xi thus makes the width xi inches. The default is to produce an image that is four inches wide. ImageSize->{x,y} scales the graphic so that it fits in an x×y region.
absolute image size in printer's points
how the image is oriented in the file
resolution in dpi for the image
Options for Export.
Within the Wolfram Language, graphics are manipulated in a way that is completely independent of the resolution of the computer screen or other output device on which the graphics will eventually be rendered.
Many programs and devices accept graphics in resolutionindependent formats such as Encapsulated PostScript (EPS). But some require that the graphics be converted to rasters or bitmaps with a specific resolution. The ImageResolution option for Export allows you to determine what resolution in dots per inch (dpi) should be used. The lower you set this resolution, the lower the quality of the image you will get, but also the less memory the image will take to store. For screen display, typical resolutions are 72 dpi and above; for printers, 300 dpi and above.
AutoCAD drawing interchange format ( .dxf )
STL stereolithography format ( .stl )
Typical 3D geometry formats supported by the Wolfram Language.
Microsoft wave format ( .wav )
μ law encoding ( .au )
sound file format ( .snd )
AIFF format ( .aif , .aiff )
Typical sound formats supported by the Wolfram Language.
Importing Graphics and Sounds
The Wolfram Language allows you not only to export graphics and sounds, but also to import them. With Import you can read graphics and sounds in a wide variety of formats, and bring them into the Wolfram Language as Wolfram Language expressions.
import graphics from the file name.ext in a format deduced from the file name
import graphics in the specified format
import graphics from a string
Importing graphics and sounds.
This imports an image stored in JPEG format:
This shows an array of four copies of the image:
This imports a sound stored in a WAV file:
Import yields expressions with different structures depending on the type of data it reads. Typically you will need to know the structure if you want to manipulate the data that is returned.
resolutionindependent graphics
resolutiondependent bitmap images
animated graphics
audio signals
Structures of expressions returned by Import.
This shows the overall structure of the graphics object imported above:
This extracts the array of pixel values used:
Here are the dimensions of the array:
This shows the distribution of pixel values:
This shows a transformed version of the image: