Mathematica Navigator 2009 3rd Edition [godsogood]

Mathematica® Navigator This page intentionally left blank Mathematica® Navigator Mathematics, Statistics, and Graphics THIRD EDITION Heikki Ruskeepää ...

10 downloads 1023 Views 19MB Size

Mathematica ® Navigator

This page intentionally left blank

Mathematica ® Navigator Mathematics, Statistics, and Graphics

THIRD EDITION

Heikki Ruskeepää Department of Mathematics University of Turku, Finland

AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Academic Press is an imprint of Elsevier

The book is produced from PDF files prepared by the author with Mathematica®. Academic Press is an imprint of Elsevier 30 Corporate Drive, Suite 400, Burlington, MA 01803, USA 525 B Street, Suite 1900, San Diego, California 92101-4495, USA 84 Theobald’s Road, London WC1X 8RR, UK Copyright © 2009, Elsevier Inc. All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopy, recording, or any information storage and retrieval system, without permission in writing from the publisher. Permissions may be sought directly from Elsevier’s Science & Technology Rights Department in Oxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333, E-mail: [email protected] You may also complete your request online via the Elsevier homepage (http://elsevier.com), by selecting “Support & Contact” then “Copyright and Permission” and then “Obtaining Permissions.” Library of Congress Cataloging-in-Publication Data Ruskeepää, Heikki. Mathematic navigator : mathematics, statistics, and graphics / Heikki Ruskeepää. – 3rd ed. p. cm. Includes bibliographical references and index. ISBN 978-0-12-374164-6 (pbk. : alk. paper) 1. Mathematics–Data processing. 2. Mathematica (Computer file) I. Title. QA76.95.R87 2009 510.285'5–dc22 2008044637 British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library. ISBN: 978-0-12-374164-6 For information on all Academic Press publications visit our Web site at www.elsevierdirect.com

Printed in the United States of America 09 10 11 9 8 7 6 5 4 3 2

1

To Marjatta

This page intentionally left blank

Contents Preface xi 1 Starting 1 1.1 What Is Mathematica 2 1.2 First Calculations 6 1.3 Important Conventions 12 1.4 Getting Help 15 1.5 Editing 22 2 Sightseeing 25 2.1 Graphics 26 2.2 Expressions 31 2.3 Mathematics 40 3 Notebooks 51 3.1 Working with Notebooks 52 3.2 Editing Notebooks 59 3.3 Inputs and Outputs 70 3.4 Writing Mathematical Documents 78 4 Files 93 4.1 Loading Packages 94 4.2 Exporting and Importing 100 4.3 Saving for Other Purposes 109 4.4 Managing Time and Memory 112 5 Graphics for Functions 115 5.1 Basic Plots for 2D Functions 116 5.2 Other Plots for 2D Functions 132 5.3 Plots for 3D Functions 139 5.4 Plots for 4D Functions 147 6 Graphics Primitives 151 6.1 Introduction to Graphics Primitives 152 6.2 Primitives and Directives 155

viii

Mathematica Navigator

7 Graphics Options 179 7.1 Introduction to Options 180 7.2 Options for Form, Ranges, and Fonts 189 7.3 Options for Axes, Frames, and Primitives 195 7.4 Options for the Curve 203 7.5 Options for Surface Plots 210 7.6 Options for Contour and Density Plots 226 8 Graphics for Data 231 8.1 Basic Plots 232 8.2 Scatter Plots 249 8.3 Bar Charts 253 8.4 Other Plots 260 8.5 Graph Plots 267 8.6 Plots for 3D Data 275 9 Data 283 9.1 Chemical and Physical Data 284 9.2 Geographical and Financial Data 293 9.3 Mathematical and Other Data 300 10 Manipulations 315 10.1 Basic Manipulation 316 10.2 Advanced Manipulation 338 11 Dynamics 357 11.1 Views and Animations 357 11.2 Advanced Dynamics 369 12 Numbers 395 12.1 Introduction to Numbers 396 12.2 Real Numbers 403 12.3 Options of Numerical Routines 409 13 Expressions 413 13.1 Basic Techniques 414 13.2 Manipulating Expressions 419 13.3 Manipulating Special Expressions 427 13.4 Mathematical Functions 435 14 Lists 443 14.1 Basic List Manipulation 444 14.2 Advanced List Manipulation 459

Contents 15 Tables 4670 15.1 Basic Tabulating 467 15.2 Advanced Tabulating 470 16 Patterns 4910 16.1 Patterns 491 16.2 String Patterns 505 17 Functions 5110 17.1 User-Defined Functions 512 17.2 More about Functions 523 17.3 Contexts and Packages 531 18 Programs 5410 18.1 Simple Programming 542 18.2 Procedural Programming 553 18.3 Functional Programming 568 18.4 Rule-Based Programming 584 18.5 Recursive Programming 596 19 Differential Calculus 6150 19.1 Derivatives 615 19.2 Taylor Series 624 19.3 Limits 630 20 Integral Calculus 6330 20.1 Integration 634 20.2 Numerical Quadrature 644 20.3 Sums and Products 666 20.4 Transforms 670 21 Matrices 6770 21.1 Vectors 677 21.2 Matrices 686 22 Equations 709 22.1 Linear Equations 710 22.2 Polynomial and Radical Equations 716 22.3 Transcendental Equations 730 23 Optimization 7410 23.1 Global Optimization 743 23.2 Linear Optimization 753 23.3 Local Optimization 759 23.4 Classical Optimization 768 23.5 Special Topics 777

ix

x

Mathematica Navigator

24 Interpolation 791 24.1 Usual Interpolation 792 24.2 Piecewise Interpolation 797 24.3 Splines 803 24.4 Interpolation of Functions 806 25 Approximation 811 25.1 Approximation of Data 812 25.2 Approximation of Functions 824 26 Differential Equations 829 26.1 Symbolic Solutions 830 26.2 More about Symbolic Solutions 841 26.3 Numerical Solutions 849 26.4 More about Numerical Solutions 865 27 Partial Differential Equations 885 27.1 Symbolic Solutions 886 27.2 Series Solutions 893 27.3 Numerical Solutions 909 28 Difference Equations 923 28.1 Solving Difference Equations 924 28.2 The Logistic Equation 935 28.3 More about Discrete Systems 950 29 Probability 961 29.1 Random Numbers and Sampling 962 29.2 Discrete Probability Distributions 966 29.3 Continuous Probability Distributions 976 29.4 Stochastic Processes 987 30 Statistics 1003 30.1 Descriptive Statistics 1004 30.2 Frequencies 1011 30.3 Confidence Intervals 1020 30.4 Hypothesis Testing 1024 30.5 Regression 1030 30.6 Smoothing 1041 30.7 Bayesian Statistics 1046 References 1063 Index 1067

Preface What is the difference between an applied mathematician and a pure mathematician? An applied mathematician has a solution for every problem, while a pure mathematician has a problem for every solution.

Welcome The goals of this book, the third edition of Mathematica Navigator: Mathematics, Statistics, Graphics, and Programming, are as follows: •to introduce the reader to Mathematica; and •to emphasize mathematics (especially methods of applied mathematics), statistics, graphics, programming, and writing mathematical documents. Accordingly, we navigate the reader through Mathematica and give an overall introduction. Often we slow down somewhat when an important or interesting topic of mathematics or statistics is encountered to investigate it in more detail. We then often use both graphics and symbolic and numerical methods. Here and there we write small programs to make the use of some procedures easier. One chapter is devoted to Mathematica as an advanced environment of writing mathematical documents. The online version of the book, which can be installed from the enclosed CD-ROM, makes the material easily available when working with Mathematica. Changes in this third edition are numerous and are explained later in the Preface. The current edition is based on Mathematica 6. On the CD-ROM, there is material that describes the new properties of Mathematica 7. ‡ Readership

The book may be useful in the following situations: •for courses teaching Mathematica; •for several mathematical and statistical courses (given in, for example, mathematics, engineering, physics, and statistics); and •for self-study. Indeed, the book may serve as a tutorial and as a reference or handbook of Mathematica, and it may also be useful as a companion in many mathematical and statistical courses, including the following: differential and integral calculus • linear algebra • optimization • differential, partial differential, and difference equations • engineering mathematics • mathematical methods of physics • mathematical modeling • numerical methods • probability • stochastic processes • statistics • regression analysis • Bayesian statistics

xii

Mathematica Navigator

‡ Previous Knowledge

No previous knowledge of Mathematica is assumed. On the other hand, we assume some knowledge of various topics in pure and applied mathematics. We study, for example, partial differential equations and statistics without giving detailed introductions to these topics. If you are not acquainted with a topic, you can simply skip the chapter or section of the book considering that topic. Also, to understand the numerical algorithms, it is useful if the reader has some knowledge about the simplest numerical methods. Often we introduce briefly the basic ideas of a method (or they may become clear from the examples or other material presented), but usually we do not derive the methods. If a topic is unfamiliar to you, consult a textbook about numerical analysis, such as Skeel and Keiper (2001). ‡ Recommendations

If you are a newcomer to Mathematica, then Chapter 1, Starting, is mandatory, and Chapter 2, Sightseeing, is strongly recommended. You can also browse Chapter 3, Notebooks, and perhaps also Chapter 4, Files, so that you know where to go when you encounter the topics of these chapters. After that you can proceed more freely. However, read Section 13.1, “Basic Techniques,” because it contains some very common concepts used constantly for expressions. If you have some previous knowledge of Mathematica, you can probably go directly to the chapter or section you are interested in, with the risk, however, of having to go back to study some background material. Again, be sure to read Section 13.1.

Contents The 30 chapters of the book can be divided into nine main parts: Introduction

Dynamics

Mathematics

1. Starting

10. Manipulations

2. Sightseeing

11. Dynamics

19. Differential Calculus 20. Integral Calculus

Files

Expressions

3. Notebooks 4. Files

12. Numbers 13. Expressions

Graphics

24. Interpolation

5. Grahics for Functions 6. Graphics Primitives

14. Lists 15. Tables 16. Patterns

7. Graphics Options

Programs

8. Graphics for Data

17. Functions 18. Programs

27. Partial Differential Equations

Data

9. Data

21. Matrices 22. Equations 23. Optimization 25. Approximation 26. Differential Equations 28. Difference Equations Statistics

29. Probability 30. Statistics

Dependencies between the chapters are generally quite low. If you read Chapter 2, Sightseeing, you will get a background that may serve you well when reading most other chapters; in some chapters, you will also find references to previous chapters, where you will find the needed background. The following bar chart shows the numbers of pages of the 30 chapters:

Preface

xiii

The six longest chapters are 7, Graphics Options; 8, Graphics for Data; 18, Programs; 23, Optimization; 26, Differential Equations; and 30, Statistics. Next we describe the main parts of the book. ‡ Introduction, Files, Graphics, Data, Dynamics, Expressions, and Programs

The first two chapters introduce Mathematica and give a short overview. The next two chapters consider files, particularly files created by Mathematica, which are called notebooks. We show how Mathematica can be used to write mathematical documents. We also explain how to load packages, how to export and import data and graphics into and from Mathematica, and how to manage memory and computing time. You may skip these two chapters until you need them. Then we go on to graphics. One of the finest aspects of Mathematica is its high-quality graphics, and one of the strongest motivations for studying Mathematica is to learn to illustrate mathematics with figures. We consider separately graphics for functions and graphics for data. In addition, we have chapters about graphics primitives and graphics options. New in Mathematica 6 are the built-in data sources, covering topics such as chemistry, astronomy, particles, countries, cities, finance, polyhedrons, graphs, words, and colors. The main new topic in Mathematica 6 is dynamics. This allows us to easily build interactive interfaces. The user of such an interface can choose some parameters or other options and the output will be changed dynamically, in real time. This helps in studying various models and phenomena.

xiv

Mathematica Navigator

Then we study various types of expressions, from numbers to strings, mathematical expressions, lists, tables, and patterns. We have two chapters relating to programming. The first studies functions and the next various styles of programming. Four styles are considered: procedural, functional, rule-based, and recursive. ‡ Mathematics and Statistics

In the remaining 12 chapters, we study different areas of pure and applied mathematics and statistics. The mathematical chapters can be divided into four classes, with each class containing chapters of more or less related topics. Descriptions of these classes follow. Topics of traditional differential and integral calculus include derivatives, Taylor series, limits, integrals, sums, and transforms. Then we consider vectors and matrices; linear, polynomial, and transcendental equations; and global, local, and classical optimization. In interpolation we have the usual interpolating polynomial, a piecewise-calculated interpolating polynomial, and splines. In approximation we distinguish the approximation of data and functions. For the former, we can use the linear or nonlinear least-squares method, whereas for the latter we have, for example, minimax approximation. Mathematica solves differential equations both symbolically and numerically. We can solve first- and higher-order equations, systems of equations, and initial and boundary value problems. For partial differential equations, we show how some equations can be solved symbolically, how to handle series solutions, and how to numerically solve problems with the method of lines or with the finite difference method. Then we consider difference equations. For linear difference equations, we can possibly find a solution in a closed form, but most nonlinear difference equations have to be investigated in other ways, such as studying trajectories and forming bifurcation diagrams. Lastly, we study probability and statistics. Mathematica contains information about most of the well-known probability distributions. Simulation of various random phenomena (e.g., stochastic processes) is done well with random numbers. Statistical topics include descriptive statistics, frequencies, confidence intervals, hypothesis testing, regression, smoothing, and Bayesian statistics.

Special Aspects The book explains a substantial portion of the topics of Mathematica. However, some topics are emphasized, some are given less emphasis, and some are even excluded. We describe these special aspects of the book here. ‡ Breadth

We have had the goal of studying important topics in some breadth and depth. This may mean detailed explanations, clarifying examples, programs, and applications. It may also mean introducing topics for which there is little or no built-in material. The headings of the chapters give a list of topics that are emphasized in this book and that are explained in some breadth. However, some emphasized topics cannot be identified from the chapter headings. One of them is numerical methods; they are used in every mathematical chapter. Another is methods relating to data. Indeed, we use several real-life and artificial data sets in chapters about data, graphics for data, approximation, differential and difference equations, probability, and statistics.

Preface

xv

‡ Depth

To give an impression of the depth of various topics, we next describe some special topics in various chapters of the book. •Chapter 3,Notebooks: An introduction to Mathematica as an environment for preparing technical documents; writing mathematical formulas •Chapter 5,Graphics for Functions: Stereographic figures; graphics for four-dimensional functions •Chapter 8,Graphics for Data: Visualizations of several real-life data; dot plots; statistical plots •Chapter 18,Programs: Four styles of programming (procedural, functional, rule-based, and recursive); emphasis on functional programming; many examples of programs •Chapter 22,Equations: Iterative methods of solving linear equations; programs for nonlinear equations •Chapter 23,Optimization: A program for numerical minimization; a program for classical optimization with equality and inequality constraints; dynamic programming •Chapter 25,Approximation: Graphical diagnostics of least-squares fits •Chapter 26,Differential Equations: Analyzing and visualizing solutions of systems of nonlinear differential equations; study of a predator-prey model, a competing species model, and the Lorenz model; numerical solution of linear and nonlinear boundary value problems; estimation of nonlinear differential equations from data; solving integral equations •Chapter 27,Partial Differential Equations: Series solutions for partial differential equations; solving parabolic and hyperbolic problems by the method of lines;solving elliptic problems by the finite difference method •Chapter 28,Difference Equations: The logistic model as an example of nonlinear difference equations; bifurcation diagrams, periodic points, Lyapunov exponents; a discrete-time predator-prey model as an example of a system of nonlinear difference equations; estimation of nonlinear difference equations from data; fractal images; Lindenmayer systems •Chapter 29,Probability: Simulation of several stochastic processes •Chapter 30,Statistics: Visualizing confidence intervals and types of errors in statistical tests; confidence intervals and tests for probabilities; local regression; Bayesian statistics; Gibbs sampling; Markov chain Monte Carlo ‡ Programs

Mathematica has a large number of ready-to-use commands for symbolic and numerical calculations and for graphics. Nevertheless, in this book we also present approximately 130 of our own programs. Indeed, programming is one of the strongest points of Mathematica. It is often amazing how concisely and efficiently we can write a program even for a somewhat complex problem. We think that our own programs can be of some value, despite the fact that they are not so fine and powerful as Mathematica’s built-in commands. We have included our own programs for the following reasons: 1.A self-made implementation shows clearly how the algorithm works. You know (or should know) exactly what you are doing when you use your own implementation. The ready-made commands are often like black (or gray) boxes because we do not know much about the methods. 2.Writing our own implementations teaches us programming. We present short programs throughout the book (especially in the mathematical chapters). In this way, we hope that you will become steadily more familiar with programming and that you are encouraged to practice program writing.

xvi

Mathematica Navigator

3.A self-made implementation can be pedagogically worthwhile. For example, we implement Euler’s method for differential equations. It has almost no practical value, but as the simplest numerical method for initial value problems, it has a certain pedagogical value. Also, programming a simple method first may help us to tackle a more demanding method later. ‡ Other Special Aspects

We have integrated the so-called packages tightly into the material covered in this book. Instead of presenting a separate chapter about packages, each package is explained in its proper context. We have tried to make the structure of the book such that finding a topic is easy. Usually a topic is considered in one and only one chapter or section so that you need not search in several places to find the whole story. Each numerical routine is also presented in the proper context after the corresponding symbolic methods. This helps you to find material for solving a given problem: It is usually best to try a symbolic method first and, if this fails, to then resort to a numerical method. Some topics of a “pure” nature, such as finite fields, quaternions, combinatorics, computational geometry, and graph theory, are not considered in this book; Mathematica has packages for these topics. Commands for box and notebook manipulation are treated only briefly. We do not consider MathLink (a part of Mathematica that enables interaction between Mathematica and external programs), J/Link (a product that integrates Mathematica and Java), XML (a metamarkup language for the World Wide Web), or MathML (an XML-based markup language for representing mathematics). Also, we do not consider any of the many other Mathematica-related products, such as webMathematica, gridMathematica, CalculationCenter, or the Applications Library packages.

Mathematica 6 ‡ Introduction

Mathematica 6 contains a huge amount of new functionality. The following is a part of an on-line document: Mathematica 6.0 fundamentally redefines Mathematica and introduces a major new paradigm for computation. Building on Mathematica’s time-tested core symbolic architecture, version 6.0 adds nearly a thousand new functions~almost doubling the total number of functions in the system~ dramatically increasing both the breadth and depth of Mathematica’s capabilities, as well as introducing hundreds of major original algorithms, and perhaps a thousand new ideas, large and small. To study the new features, see the following on-line documentation (the use of the Documentation Center is explained in Section 1.4.2, p. 17): • Help @ Startup Palette, the What’s New in 6 link to Wolfram’s website • Help @ Documentation Center, the New in 6 links in the home page • Help @ Documentation Center, the guideêSummaryOfNewFeaturesIn60 document • Help @ Documentation Center, the guideêNewIn60AlphabeticalListing document • Help @ Function Navigator, the New In 6 item If you are a new user of Mathematica and would like to study the basics of Mathematica 6, see the following documents: • Help @ Startup Palette: the First Five Minutes with Mathematica button • Help @ Virtual Book: the Introduction item

Preface

xvii

‡ New Properties of Version 6

Because the new features are numerous, we do not list them all here. However, we mention some of the most remarkable new commands and features, classified according to the chapters of the book: •Chapter 1, Starting: documentation is on-line in the form of Documentation Center, Function Navigator and Virtual Book (we do not have a printed manual); documentation is automatically updated via the Internet; writing Mathematica inputs is helped by syntax coloring •Chapter 3, Notebooks: Style, Text, Hyperlink •Chapter 4, Files: commands of many packages are now built-in; the remaining packages are rebuilt; look at Compatibility/guide/StandardPackageCompatibilityGuide in the Documentation Center to obtain information about how to replace the functionality of the old packages •Chapter 5, Graphics for Functions: GraphicsRow, GraphicsGrid, Tooltip; graphics is handled like other expressions; the default font in graphics is Times instead of Courier; 3D graphics is adaptive; contours in contour plots have tooltips; density plots, by default, do not have meshes; 2D graphics can be interactively drawn and edited; 3D graphics can be interactively manipulated (e.g., rotated); for animation, use Manipulate or Animate •Chapter 6, Graphics Primitives: Arrow, Opacity, Inset •Chapter 7, Graphics Options: Directive, BaseStyle, Filling; the default value of AspectRatio in Graphics and ParametricPlot is Automatic instead of 1/GoldenRatio •Chapter 8, Graphics for Data: ListLinePlot, GraphPlot; plotting of several data sets •Chapter 9, Data: ElementData, CountryData, PolyhedronData, etc. •Chapter 10, Manipulations: Manipulate (for creating interactive dynamic interfaces) •Chapter 11, Dynamics: Dynamic (for advanced dynamic interfaces), MenuView, TabView, etc. •Chapter 15, Tables: Grid, Row, Column •Chapter 16, Patterns: DictionaryLookup •Chapter 21, Matrices: Accumulate, PositiveDefiniteMatrixQ •Chapter 23, Optimization: FindShortestTour •Chapter 29, Probability: RandomReal, RandomInteger, RandomChoice, RandomSample •Chapter 30, Statistics: Tally, BinCounts, FindClusters In my opinion, the most impressive new commands in version 6 are Manipulate, Dynamic, GraphPlot, and Grid.

Note that many familiar commands, such as NIntegrate or NDSolve, have also been enhanced in version 6. In the forthcoming chapters, we mark with (Ÿ6) the properties and commands of Mathematica available for the first time in version 6. ‡ Obsolete Properties in Version 6

Version 6 makes obsolete some old commands and features, especially in graphics. First, here are some changes that relate to the display and arrangement of graphics: •To prevent the display of graphics, end the plotting command with ; instead of using the DisplayFunction option. •In programs, enclose a plotting command with Print if that command is not the last command of the program and you would like the program to show that plot. •GraphicsArray is obsolete. To show, for example, two plots p1 and p2 side by side, use one of the following ways: {p1, p2}, Row[{p1, p2}], or GraphicsRow[{p1, p2}]. Use GraphicsGrid for arrays of plots.

xviii

Mathematica Navigator

•To show two plots side by side, you can also simply give a list of plotting commands {Plot[…], Plot[…]}. •To show two plots on top of each other, simply write Show[Plot[…], Plot[…]]; the DisplayFunction option is no longer needed. •Graphics and Graphics3D no longer need Show to display the graphics. Thus, write Graphics[{…}] instead of Show[Graphics[{…}]. •Use Inset[gr, pos] instead of Rectangle[{x1, y1}, {x2, y2}, gr]. Some changes that relate to plotting of data are as follows: •To plot data by connecting the points with lines, use ListLinePlot[data] instead of ListPlot[data, PlotJoined Ø True]. •To plot data by points and connecting lines, use ListLinePlot[data, Mesh Ø All] instead of ListPlot[data, PlotJoined Ø True, Epilog Ø {PointSize[s], Map[point, data]}]. •To plot data by points and vertical lines, use ListPlot[data, Filling Ø Axis] instead of resorting to Prolog or Epilog. •To plot several data sets, use ListPlot[{data1, data2, … }] or ListLinePlot[{data1, data2, … }] instead of resorting to MultipleListPlot in a package. •To plot several points, simply write Point[points] instead of Map[Point, points]. Here are some changes that relate to styles and options of graphics: •Use Style instead of StyleForm. •Use the BaseStyle option instead of the TextStyle option or the $TextStyle global constant. •Use the MaxRecursion option instead of the PlotDivision option. •Use the DataRange option instead of the MeshRange option. •Use the Filling option instead of the FilledPlot command. Some other changes are as follows: •Use RandomReal[…], RandomInteger[…], and RandomComplex[…] instead of Random[Real, …], etc. •For random numbers from probability distributions, use RandomReal[contDist, n] or RandomInteger[discrDist, n] instead of resorting to Random or RandomArray. •Use Tally instead of Frequencies in a package.

The Third Edition ‡ Main Changes

The text has been revised throughout. Indeed, Mathematica 6 brings up so much new and changed features that almost every topic has undergone a revision and new topics are included. Recall that the second edition of this book was based on Mathematica 5. The main change in the structure of the book is that we have six new chapters: Chapter 6, Graphics Primitives; Chapter 9, Data; Chapter 10, Manipulations; Chapter 11, Dynamics; Chapter 15, Tables; and Chapter 16, Patterns. On the other hand, some chapters have been merged and the result is that the current edition has but one chapter about the following topics: graphics for functions, graphics for data, and graphics options (the second edition had two chapters for each of these topics, one for twodimensional and one for three-dimensional graphics).

Preface

xix

The main change in the contents of the book is the transition from version 5 to version 6. In addition, we have some other enhancements. The chapter on programming is much enhanced and enlarged and contains much more examples. The chapter about matrix calculus is also enhanced. The chapter about optimization now includes the method of dynamic programming. Chapters about graphics for data and optimization have undergone a restructuring. Note that this book fully utilizes the new features of Mathematica 6. Because version 6 differs so much from earlier versions, this book cannot practically be used with older versions of Mathematica. If you have Mathematica 5.2 or an earlier version, please use the second edition of Mathematica Navigator. The CD-ROM contains Help Browser material that describes the new properties of Mathematica 7. ‡ Some Notes

New Features Some of the new features of version 6 would have warranted a broader and deeper treatment and more examples of use throughout the book. These features include the creation of dynamic interfaces and the use of the built-in data sources. However, to keep the book at a reasonable size, we had to limit the treatment and the number of examples. We suggest that the reader consults the built-in documentation. The website http://demonstrations.wolfram.com contains thousands of examples of dynamic interfaces. Environment During the writing of this book, I used a Macintosh with MacOS X. Mathematica works in much the same way in various environments, but the keyboard shortcuts of menu commands vary among different environments. To some extent, we mention the shortcuts for the Microsoft Windows and Macintosh environments. Options Many commands of Mathematica have options for modifying them. All options have a default value, but we can input other values. When listing the options, we give either all possible values of them or some examples of possible values, but we do not explicitly mention the default values, to save space. In the context of this book, the default value of an option is always the first value mentioned. After that are other possible values or examples of other values. Simulations In several places in the book, we simulate various random phenomena. Usually, each time a simulation is run, a slightly different result is obtained. However, in experimenting with the examples of the book, the reader may want to get exactly the same result as printed in the book. This can be achieved by using a seed to the random number generator with SeedRandom[n] for a given integer n. With the same seed, the result of a simulation remains the same in repeated executions. We use SeedRandom quite often in this book. If you want to get other results of simulation than those of this book, give different seeds or do not execute SeedRandom[n] at all (in the latter case, the default seed is used). CD-ROM The entire book is contained on the CD-ROM that comes with it. With a few easy steps you can install the book into the Help Browser of Mathematica (the CD-ROM contains installation instructions). With the Help Browser you can easily find and read sections of the book, experiment with the commands, and copy material from the book to your document. You can see all of the figures of the book in color and interactively study the manipulations and animations. The material about the new properties of Mathematica 7 can also be installed into the Help Browser. In addition, the CD-ROM contains some data files that are used in the book.

xx

Mathematica Navigator

Notation Throughout the book, the adjectives one-, two-, three-, and four-dimensional are abbreviated 1D, 2D, 3D, and 4D, respectively. The symbol Ö is used as a hyphen for Mathematica commands. In addition, we use extensively the following handy short notation: p Means the same as Pi. The symbol p can be written as ÂpÂ. ¶ Means the same as Infinity. The symbol ¶ can be written as ÂinfÂ.

P…T Means the same as [[…]]. For example, x[[3]] can also be written as xP3T. The symbols P and T can be written as Â[[Â and Â]]Â.

¨ Means the same as Transpose. For example, Transpose[x] can also be written as x¨. The symbol ¨

can be written as ÂtrÂ.

/@ Means the same as Map. For example, Map[f[#]&, {a, b, c}] can also be written as f[#]& /@ {a, b, c}. A third way is to write Table[f[x], {x, {a, b, c}}].

The symbols p and ¶ can also be found from the BasicMathInput palette. For example, instead of [email protected]Ò ^ 2 &, [email protected], Infinity<
99p2 =, 8¶<=

we can write

Ò ^ 2 & êü 88p, ¶<<¨ 99p2 =, 8¶<=

Questions If you have questions about the use of Mathematica, do not hesitate to contact me. I try to answer when I have the time. Also, please send comments and corrections.

Acknowledgments In preparing this book, the main source has been the excellent on-line Documentation Center of Mathematica 6. The technical support staff at Wolfram Research, Inc., helped me a lot; I especially thank Eric Bynum, Roberto Cavaliere, Huihua Huang, Yong Huang, Vivec Joshi, and Bruce Miller. The entire book was written and produced with Mathematica; each chapter is a Mathematica notebook. The notebooks were connected into a single project by the AuthorTools package of Mathematica. The package then automatically generated the index (after we had attached the index entries with the cells of the book, also with the package), and the package also prepared the on-line Help Browser version of the book. I have been lucky enough to enjoy excellent working conditions at the Department of Mathematics of the University of Turku. For this my sincere thanks are due to Professor Marko Mäkelä. I also thank Professor Juhani Karhumäki and Professor Matti Vuorinen for their support and encouragement. The third edition is also published in India. I am deeply indepted to Professor Ponnusamy Saminathan, Indian Institute of Technology, Madras, Chennai, for suggesting and supporting the Indian edition. For their review of the manuscript of the second edition, I am very thankful to Donald Balenovich, Indiana University of Pennsylvania; Joaquin Carbonara, Buffalo State University; William Emerson, Metropolitan State University; Jim Guyker, Buffalo State University; Mike Mesterton-Gibbons, Florida State University; and Fred Szabo, Concordia University. Their valuable comments and suggestions greatly improved the second edition.

Preface

xxi

I also thank the following people for taking the task of writing a review of the second edition of the book in some journals: Robert M. Lurie (Mathematica in Education and Research), Matti Vuorinen (Zentralblatt MATH), K. Waldhör (Computing Reviews), and John A. Wass (Scientific Computing). Many readers of the second edition have sent me e-mail, giving feedback and asking questions. Thank you all! Your support has encouraged me in writing the third edition. The anecdotes at the beginning of the chapters are from the wonderful book by MacHale (1993) (the anecdotes are reproduced or adapted with the permission of the publishers, Boole Press, 26 Temple Lane, Dublin 2, Ireland). The editorial staff at Elsevier has done a fine work with the production of the book. Especially I would like to thank Phil Bugeau for efficient project management. I am also very grateful to Dan Hays and Kristen Cassereau Ng for copy-editing and proofreading the manuscript with great care. For financial support I express my deep gratitude to Elsevier Academic Press and Suomen Tietokirjailijat (The Association of Finnish Non-Fiction Writers). Lastly, I thank my wife, Marjatta, for her encouragement and support during the work.

Heikki Ruskeepää Department of Mathematics University of Turku FIN-20014 Turku Finland [email protected]

xxii This page intentionally left blank

Mathematica Navigator

1 Starting Introduction 1 1.1 What Is Mathematica? 2 1.1.1 An Example 2 1.1.2 The Structure of Mathematica 4 1.2 First Calculations 6 1.2.1 Opening, Calculating, and Quitting 6 1.2.2 Names and Decimals 7 %, Out, N 1.2.3 Basic Calculations and Plotting 10 Pi, E, Sqrt, Exp, Sin, D, Integrate, Simplify, Plot, etc. 1.3 Important Conventions 12 1.4 Getting Help 15 1.4.1 Palettes 15 1.4.2 On-line Documentation 17 1.4.3 Other Help 20 ? 1.5 Editing 22

Introduction In 1903 at a meeting of the American Mathematical Society, F. N. Cole read a paper entitled “On the Factorization of Large Numbers.” When called upon to speak, Cole walked to the board and, saying nothing, raised two to its sixty-seventh power and subtracted one from the answer. Then he multiplied, longhand, 193,707,721 by 761,838,257,287 and the answers agreed. Without having said a word, Cole sat down to a standing ovation. Afterwards he announced that it had taken him twenty years of Sunday afternoons to factorize the Mersenne number 267 - 1. This chapter is intended to give you an impression of Mathematica and to teach you some of its basic techniques and commands. A more complete insight is given in the next chapter, in which we briefly present a selection of the most important commands of Mathematica. Although this book puts some emphasis on the methods of applied mathematics, this chapter begins, in Section 1.1, with a “pure” example: factoring integers. We consider the problem mentioned in the anecdote above and show what we can do nowadays with such powerful systems as Mathematica. This example will enlighten you regarding some of the major aspects of the program. We emphasize that it is not intended that you do the calculations of this example, nor that you should understand the commands we use. In Section 1.2, we give a brief overview of some of Mathematica’s basic techniques and commands, beginning with the classical starting example of calculating 1+2 and ending with calculus and graphics. Section 1.3 presents and explains the important conventions of Mathematica, which often cause trouble for beginners.

2

Mathematica Navigator

In Sections 1.4 and 1.5, we discuss how you can get help within Mathematica and how you can correct and edit what you have written. These two sections may give more information than you need now, but you can read the basic points and return to these sections later, when getting help and editing become more relevant concerns. Parts of this chapter depend on the computer you use. We explain only the Windows and Macintosh environments, although some comments may be found about the basics of Mathematica in a Unix system.

1.1 What Is Mathematica? 1.1.1 An Example ‡ Verifying the Work of Cole

(Note: It is not intended that you do the calculations of Section 1.1.1. The example is only intended to be read and to demonstrate certain aspects of Mathematica. Your actual lessons begin in Section 1.2.) Did you read the anecdote about F. N. Cole at the beginning of this chapter? Cole sacrificed every Sunday afternoon for 20 years to study the Mersenne number M67 = 267 - 1: 2 ^ 67 - 1 147 573 952 589 676 412 927

The first line is the command entered to Mathematica, and the second line is the answer given by Mathematica. At last he found that the number is the product of 193,707,721 and 761,838,257,287: 193 707 721 * 761 838 257 287 147 573 952 589 676 412 927

M67 is thus not a prime. Cole’s feat was admirable. Now, after 100 years, we have Mathematica, and the situation is totally different. It now takes only a fraction of a second to do the factorization: [email protected] ^ 67 - 1D êê Timing

80.016942, 88193 707 721, 1<, 8761 838 257 287, 1<<<

Mathematica found that 193,707,721 and 761,838,257,287 are factors of multiplicity 1. ‡ Difficult Factors

However, even today some problems can be surprisingly difficult. When Mathematica, in my computer (which is not very fast), factorizes M254 , it needs approximately 10,000 seconds or 3 hours and approximately 200 megabytes of RAM:

[email protected] ^ 254 - 1D êê Timing

810 521.7, 883, 1<, 856 713 727 820 156 410 577 229 101 238 628 035 243, 1<, 8170 141 183 460 469 231 731 687 303 715 884 105 727, 1<<< [email protected] 207 758 616

However, note that M254 is very big: 2 ^ 254 - 1 28 948 022 309 329 048 855 892 746 252 171 976 963 317 496 166 410 141 009 864 396 001 978 282 Ö 409 983

and two of the three factors are also big. Thus, factoring the number is obviously a difficult task. By the way, the difficulty of factoring large numbers is a key to some cryptographic methods.

Chapter 1 • Starting

3

However, for M254 , Mathematica can immediately tell that it is not a prime: [email protected] ^ 254 - 1D êê Timing 80.000223, False<

Indeed, we can easily investigate Mersenne numbers for primality up to, for example, index 607: Hmp = [email protected], [email protected] ^ i - 1D<, 8i, 2, 607
The indices for which the corresponding Mersenne number is a prime are as follows: [email protected], Ò@@2DD ã True [email protected]@All, 1DD

82, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607<

‡ A Demanding Computation

To further illustrate the use of Mathematica, we now factor the Mersenne numbers M2 to M250 . (Note that you are not supposed to do the calculations in this example. Just cast an admiring glance at the commands. Later in this book you will learn such commands as Total, /@, and Range.) We do not show the factors themselves; we only count the number of factors: Ht = [email protected]@2 ^ Ò - [email protected]@All, 2DDD & êü [email protected], 250DL êê Timing

85430.6, 81, 1, 2, 1, 3, 1, 3, 2, 3, 2, 5, 1, 3, 3, 4, 1, 6, 1, 6, 4, 4, 2, 7, 3, 3, 3, 6, 3, 7, 1, 5, 4, 3, 4, 10, 2, 3, 4, 8, 2, 8, 3, 7, 6, 4, 3, 10, 2, 7, 5, 7, 3, 9, 6, 8, 4, 6, 2, 13, 1, 3, 7, 7, 3, 9, 2, 7, 4, 9, 3, 14, 3, 5, 7, 7, 4, 8, 3, 10, 6, 5, 2, 14, 3, 5, 6, 10, 1, 13, 5, 9, 3, 6, 5, 13, 2, 5, 8, 14, 2, 11, 2, 10, 11, 6, 1, 15, 2, 12, 6, 11, 5, 9, 6, 9, 9, 6, 6, 17, 4, 3, 5, 8, 5, 14, 1, 9, 5, 9, 2, 15, 3, 5, 10, 11, 2, 9, 2, 16, 6, 6, 6, 19, 5, 6, 7, 10, 2, 14, 5, 11, 8, 10, 8, 18, 4, 5, 8, 13, 7, 16, 5, 10, 10, 8, 2, 19, 4, 7, 7, 10, 4, 11, 9, 14, 6, 5, 3, 24, 4, 11, 5, 11, 5, 8, 5, 10, 10, 10, 5, 16, 3, 7, 8, 11, 2, 17, 2, 20, 6, 4, 7, 20, 6, 5, 9, 12, 6, 22, 3, 10, 7, 4, 8, 21, 6, 5, 7, 19, 4, 13, 6, 16, 14, 10, 2, 17, 4, 12, 10, 12, 4, 16, 7, 13, 8, 11, 6, 23, 2, 8, 10, 9, 7, 12, 6, 12, 5, 11<< [email protected]

83 409 352

Thus, for example, M4 has two factors, and M250 has 11 factors. The computations took approximately 1.5 hours and approximately 80 megabytes of RAM. ‡ A Graphic Illustration

We continue studying Mersenne numbers and now form pairs from the indices and the numbers of factors: s = [email protected], 250D, t<¨;

(Here,  means a transpose.) Then we find a logarithmic least-squares fit for the number of factors as a function of the index of the Mersenne numbers: lsq = [email protected], 81, [email protected]<, iD -3.05399 + 2.25251 [email protected]

We then plot the fit and the numbers of factors:

p1 = [email protected], 8i, 2, 250<, PlotStyle Ø BlackD; p2 = [email protected], PlotStyle Ø Black, Mesh Ø All, MeshStyle Ø 8Black, [email protected]
4

Mathematica Navigator [email protected], p2, AspectRatio Ø 0.3, PlotRange Ø 8-1, 25<, ImageSize Ø 420, Ticks Ø [email protected]<, [email protected], 250, 10DD, 81, 5, 10, 15, 20, 24<
10

20

30

40

50

60

70

80

90 100 110 120 130 140 150 160 170 180 190 200 210 220 230 240 250

So, here are the numbers of factors of M2 to M250 , together with the logarithmic fit. In the figure we see the prime Mersenne numbers with indices 2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, and 127. These Mersenne primes had all been found by 1913. After the index 127, primes are not very common among Mersenne numbers. The next known primes occur with indices 521 (found in 1952); 607; 1279; 2203; 2281; 3217; 4253; 4423; 9689; 9941; 11,213; 19,937; 21,701; 23,209; 44,497; 86,243; 110,503; 132,049; 216,091; 756,839; 859,433; 1,257,787; 1,398,269; 2,976,221; 3,021,377; 6,972,593; 13,466,917; 20,996,011; 24,036,583; 25,964,951; 30,402,457 (found in 2005); 32,582,657 (found in 2006). ‡ Lessons Learned

The preceding examples show how easy it now is to do long and complicated calculations and to visualize the results. Mathematica is one of the more popular systems for doing such calculations. However, even today, with powerful mathematical systems and machines, some problems remain very time-consuming. The example also illustrates some aspects of Mathematica, such as working with exact and approximate quantities, using graphics, and making programs. In general, Mathematica integrates symbolic calculation, numerical calculation, graphics, and programming into one system. Mathematica contains still another aspect: a document-making environment (in versions of Mathematica that support the notebook interface). In this environment, you can do symbolic and numerical calculations, produce graphics, and add text to explain what you have done. The result is a complete document of your work; in fact, this book was written with Mathematica. In addition, the document is interactive. You can change parameters and functions, redo calculations, show animations, create interactive graphical interfaces, and continuously develop the document. The notebook interface is included in both Windows and Macintosh versions of Mathematica. In plain Unix, the interface is textbased and thus all features of Mathematica are not supported, but the X Window System supports notebooks.

1.1.2 The Structure of Mathematica Mathematica is a large system: The total installation of Mathematica takes up approximately 1.1 gigabytes (Gb) of space on the hard drive. The following are the essential parts of Mathematica: •the kernel, with the name MathKernel; •the front end, with the name Mathematica; and • the packages, with the name Packages. Next we consider each of these three components individually.

Chapter 1 • Starting

5

‡ The Kernel

The main component of Mathematica is the kernel; it does all of the computations. It is written mainly with the C programming language and is one of the largest mathematical systems ever written. The total number of lines of code in the kernel is approximately 2.5 million. An important thing to understand is that the kernel is the same in all environments; this means that you get the same results in all environments (except possibly for the precision of floating-point calculations). Mathematica commands are easy to use and quite versatile. However, behind the commands there is a huge amount of mathematical knowledge and a vast amount of work. For example, behind the single command Integrate, there are approximately 600 pages of C code and 500 pages of Mathematica code. ‡ The Front End

The front end is an environment for communicating with the kernel. When you open Mathematica, you open the front end. Commands are entered into the front end, and they are sent automatically to the kernel (the communication between the front end and the kernel is done with MathLink, a system that handles communication between parts of Mathematica and between Mathematica and other programs). The result of a calculation is then displayed by the front end. Figures come from the kernel in the form of PostScript code, and the front end then creates a screen image from this code. The front end contains approximately 700,000 lines of system-independent C++ source code. There are two types of front ends: notebook and text-based. A notebook front end is, for example, in the Windows, Macintosh, and X Window versions of Mathematica. A notebook is an interactive document. It contains the commands you have entered and their results, graphics (including animations), dynamic graphical interfaces, and comments you have added. You can do any kind of correcting, editing, and formatting in a notebook. In fact, you can make a notebook into a whole document of your work, even a book. (The chapters of this book were made as separate notebooks.) The text-based front end is not nearly so handy and versatile as the notebook front end. This type of front end is found in the plain Unix version of Mathematica. With this kind of front end you can enter commands and see the results, but editing is very limited. Another disadvantage is that pictures are displayed in separate windows. ‡ The Packages

The packages supplement the kernel. They are not normally loaded when Mathematica is loaded; you have to manually load the packages you want to use. Packages contain commands considered not to be as central and as common as the commands in the kernel. Packages are written using the programming capabilities of Mathematica. To the packages that come with Mathematica you can also add the vast collection of packages and other material found at http://library.wolfram.com/. In addition, you can write your own packages and programs. Furthermore, there are collections of Wolfram application packages and third-party application packages; see www.wolfram.com/products.

6

Mathematica Navigator

1.2 First Calculations 1.2.1 Opening, Calculating, and Quitting ‡ Opening Mathematica

To open Mathematica, do the following: •In Windows and Macintosh environments: open Mathematica as other programs •In Unix with X Window: type mathematica •In plain Unix: type math When you open Mathematica in a notebook environment, you get an empty notebook. A cursor appears once you have pressed the first key. ‡ Calculating

Now, are you ready to begin? Let us start modestly and try to calculate 1 + 2. Press these three keys: 1+2

The command is executed (i.e., sent to the kernel for processing) by pressing a special key or key combination. To execute a command, press Û or ˜÷Á In Windows and Macintosh interfaces, both ways work (Û is the key at the bottom right corner of the keyboard; ˜÷Á means that you are holding down the Shift key while at the same time pressing the Return key ¿). In Unix, it may be that ˜÷Á is the only possibility. Note that although we have spoken about “executing a command,” this is not in keeping with the official terminology. We should speak about “evaluating an input.” You should know the official term evaluation, but we ourselves feel free to use the more concrete term execution. So, after typing the command or input 1 + 2, press any of the executing or evaluating keys or key combinations. Now the kernel begins to evaluate the input. In most microcomputers, the kernel is not loaded until you ask it to do a calculation. This means that the first calculation takes some time, even if it is as simple as 1 + 2. After you have entered the input, the label In[1]:= appears before the input, and the result has the label Out[1]=. You get 1+2 3

Note that here we do not show the In and Out labels. Indeed, by adjusting the preferences of Mathematica, we can turn the labels off. In a Macintosh, the preferences can be found from the Mathematica @ Preferences… menu. Go then into the Evaluation preferences and click Show In/Out names to be off. The input and the output can be distinguished by the font: The input is in boldface Courier, whereas the output is in plain Courier. Try the next command (note that although you again cannot see a cursor in the notebook, just start typing; the new command appears where you see a horizontal line): 18 ê 4 9 2

Chapter 1 • Starting

7

Fractions are automatically simplified, and they are written in a 2D form (instead of 9 ê 2). If the expression contains a decimal number, then the result is also a decimal number: 10 ê 3.

3.33333 ‡ Correcting

You may observe an error in a command when you write it, or after executing the command Mathematica may give you an error message telling you that there is something wrong with the command. In a notebook environment (e.g., Windows, Macintosh, or X Window), you can do standard editing as with a word processor. For example, to delete an incorrect character, just move the cursor to the desired location by pressing the arrow keys or with the mouse and press the backspace key or the delete key to remove the character to the left or right, respectively. You can also highlight a portion of an input, cut it (‚ÎxÏ; on a Macintosh, use Ì in place of ‚) or copy it (‚ÎcÏ), and then paste it (‚ÎvÏ) to a new location. Once you have a corrected input, execute it. Note that after correcting a command you can leave the cursor where it is and then execute the command; the cursor need not be at the end of the command when you execute it. We consider editing in more detail in Section 1.5, p. 22. (In plain Unix, possibly only the backspace key can be used to edit the input; arrow keys may not function. Using special editing commands such as Edit together with an editor such as Emacs can help a lot in plain Unix.) ‡ Quitting Mathematica

To quit Mathematica, do the following: •In Windows, Macintosh, and X Window: quit Mathematica as other programs •In plain Unix: execute the command Quit Do not quit right now. Instead, continue reading and experimenting. ‡ Aborting a Calculation

You may sometimes observe that a calculation is useless (perhaps because there was an error in the input or you do not have time to wait for the answer). You can then abort the calculation. To abort a calculation, do the following: • In Windows, Macintosh, and X Window: choose Abort Evaluation from the Evaluation menu, or press ‡Î.Ï (ÌÎ.Ï on a Macintosh) • In plain Unix: press ‚Î c Ï Á a Á It may happen that when you try to abort a calculation it seems that the calculation just goes on and on. You can then quit Mathematica (after possibly saving the notebook) and start a new session. In notebook environments, you can also only quit the kernel by choosing Evaluation @ Quit Kernel @ Local. Start a new session by executing an input or by choosing Evaluation @ Start Kernel @ Local.

1.2.2 Names and Decimals ‡ Before Continuing

Now we continue exploring Mathematica. Please note the following very important point:

8

Mathematica Navigator •When you try the examples of the book with your machine, write the commands exactly as they are printed here.

Mathematica will not forgive even the smallest error in syntax. Be especially careful with small and capital letters: All Mathematica names such as Sin or Integrate begin with a capital letter. Also, you have to write all arguments in functions and commands in square brackets [ ], for example, Sin[x] and Integrate[a + b x, x]; parentheses ( ) are not allowed. Parentheses are only used for grouping terms in expressions. Note that Mathematica automatically adds spaces in some places in your input (e.g., around + or =). You probably will occasionally get error messages and wrong results because the syntax was not correct. Do not worry. This is normal. Getting used to Mathematica takes time, and only by working with the program can you learn to use it efficiently. During a session, do not just enter one input after another in a hurry. Think carefully about each input and each result~how the input is written and what the result is. In this way, you will learn more effectively. Also, once you have tried some of the examples in this book, you can try other examples. This is recommended because by trying similar examples you strengthen your skills and get a clearer impression of each command and technique. ‡ Referring to Earlier Results % Refers to the last result %% Refers to the next-to-last result %%...% Refers to the kth previous result if there are k % marks Out[n] or %n Refers to the result in the output line Out[n]

Often you want to refer to earlier results. The percent mark % and the output names can be used for this. Try the following commands: 353 ^ 4 15 527 402 881 30 ^ 4 + 120 ^ 4 + 272 ^ 4 + 315 ^ 4 15 527 402 881 %% - % 0

Try also the output names by executing, for example, Out[4] + Out[5] or %4 + %5. Using % can become a problem if the command you execute contains errors to be corrected. Suppose you first calculate 16 ^ 2 256

Then you want to calculate 162 - 152 , but you write % + 15 ^ 2 481

If you now correct the command to read % - 15^2, you do not get what you want because % now refers to the result 481 of the last (wrong) command. So, you have to correct the command to read %% - 15^2.

Chapter 1 • Starting

9

In general, if you correct several times a command that originally contained a %, you have to add one % each time. This may become awkward. It may be clearer to assign names to expressions, as explained

later. A way to refer to the last command and its result is to choose Insert @ Input from Above or Insert @ Output from Above. ‡ Giving Names a = value Assign value for a a Show the value of a a =. Clear the value of a

Another technique for referring to earlier results is to give names to results. Later, you can use the names as needed. For example, what is the probability of getting two 6’s when tossing a die six times? a = [email protected], 2D 15

b = H1 ê 6L ^ 2 * H5 ê 6L ^ 4 625 46 656 c = a*b 3125 15 552

You can always ask the value of a variable simply by entering the name of the variable: a 15

When a symbol is no longer used, it is useful to clear the value of the variable so that it does not cause trouble later: a =.

Now a has no value, as we see if we ask the value of a: a a

Mathematica printed only the name of the variable. Note that we can see from the color of a symbol whether it has a value: A blue symbol does not have a value, whereas a black symbol does have a value. ‡ Decimal Values expr//N or N[expr] Calculate a decimal value for expr

You have perhaps noted that all calculations with integers and fractions are kept in an exact form; a decimal value is not automatically computed. A decimal value can be asked for with N. It can be used in two equivalent forms. The form expr//N may be easier to write than the form N[expr]. For example,

10

Mathematica Navigator b 625 46 656 % êê N 0.0133959 c êê N

0.200939 [email protected] 0.200939

We can also ask directly for the decimal value (without first asking for a simplified fraction): H1 ê 6L ^ 2 * H5 ê 6L ^ 4 êê N 0.0133959

Note that, from now on, we here and there show the results of commands next to each command to save space.

1.2.3 Basic Calculations and Plotting ‡ Basic Arithmetic a+b

a-b

a b or a*b

a/b

a^b

The basic arithmetic operations plus, minus, division, and power are expressed in the usual manner, but multiplication is different. With Mathematica, multiplication is usually expressed by a space (press the space bar once). If you are more comfortable with the asterisk *, you can use it. For example, a=5

5

b=3

3

ab

15

Note that if you write ab without a space, Mathematica treats this as a single variable with the name ab: ab

ab

We have not defined a value for the variable ab, so Mathematica just writes the name of the variable. This is a common error when using Mathematica. You have to write a b with a space or a*b with an asterisk if you want multiplication. Multiplication is explained further in Section 1.3, p. 13. ‡ Basic Constants Pi, E, I, Infinity

These well-known constants are usually denoted by p, e, i, and ¶ in mathematical texts. For example, Pi êê N E êê N I^2

3.14159 2.71828 -1

Chapter 1 • Starting 1 ê Infinity

11

0

Negative infinity is -Infinity. Note that Mathematica writes Pi as p, E as ‰, I as Â, and Infinity as ¶: 8Pi, E, I, Infinity< 8p, ‰, Â, ¶<

We can also write Pi as p, Infinity as ¶, and so on by using the Escape key, as follows: To write p, type Âp To write ¶, type Âinf Just press the Â, p, and  keys in turn. From now on in this book, we write Pi as p and Infinity as ¶. ‡ Basic Functions Sqrt[z] or z^(1/2)

(square root) (exponential function) Log[z], Log[b, z] (natural logarithm and logarithm to base b) Abs[z] (absolute value) Exp[z] or E^z

Sin[z], Cos[z], Tan[z], Cot[z], Sec[z], Csc[z] ArcSin[z], ArcCos[z], ArcTan[z], ArcCot[z], ArcSec[z], ArcCsc[z] n!, Binomial[n, m] Max[{x, y, ...}], Min[{x, y, ...}]

Note that the natural logarithm is Log[z]. [In many mathematical texts, log(z) means a logarithm to base 10, whereas the natural logarithm is denoted by ln(z).] The arguments in trigonometric functions are in radians, and the values of the inverse trigonometric functions are in radians. Binomial gives the binomial coefficient. Max and Min give the maximum and the minimum of the arguments. For example, [email protected]@[email protected] [email protected] ê 4D

x

1 2

[email protected] ê [email protected]

p 4

We throw a die 10 times and find the maximum of the results: a = [email protected], 6<, 10D 83, 5, 2, 4, 3, 4, 3, 1, 5, 4< [email protected]

5

The value of the variable a is a list~an ordered collection of elements enclosed in curly braces {}. ‡ Basic Calculus D[expr, x] Derivative of expr with respect to x Integrate[expr, x] Indefinite integral of expr with respect to x Integrate[expr, {x, a, b}] Definite integral of expr with respect to x from a to b Simplify[expr] or expr//Simplify Simplify the expression

12

Mathematica Navigator

Again a note about terminology. We have spoken about commands such as D or Integrate, but the official term is a function. However, we feel free to speak about commands and use the term function mainly for such expressions as Sin[x], which are official mathematical functions. For example, x [email protected] + [email protected]

[email protected] [email protected], xD

[email protected] ^ 2 [email protected], 8x, 0, 1
-2 + ‰ x

p

-

r

q [email protected] + r xD r2

We check the last integral by calculating the derivative of the result: 1 [email protected]%, xD

p r

-

q

r Hq + r xL

After simplification, we get the desired result: % êê Simplify

px q+rx

‡ Basic Plotting Plot[expr, {x, a, b}] Plot expr when x takes on values from a to b

Mathematica has many plotting commands, but Plot is the basic one. An example: [email protected]@-xD [email protected] xD, 8x, 0, 2 p
1

2

3

4

5

6

In notebooks, plotting is this easy. You can also change the size of a figure: Click on it and then drag one of the handles. In plain Unix, things may be not so simple. Ask for more information from a person who knows your environment. Congratulations! Now you have used Mathematica for some simple calculations and you have an impression of how Mathematica works. We will give you a better overview of Mathematica in Chapter 2. However, first, in Section 1.3, we summarize the basic conventions of Mathematica. Then we explain, in Section 1.4, how you can get information about the commands of Mathematica. Section 1.5 considers writing, correcting, and editing in Mathematica.

1.3 Important Conventions You have observed that all of the built-in Mathematica names we have presented have begun with a capital letter and that all arguments have been given in square brackets [ ]. These are two of the most important conventions in Mathematica. Here are the six most important ones:

Chapter 1 • Starting

13

•All built-in Mathematica names begin with a capital letter. •Multiplication must be expressed by a space or an asterisk (*). (For numerical multipliers or complete expressions, nothing is needed.) •All arguments are given in square brackets [ ]. •Parentheses ( ) are used only for grouping terms. •Curly braces { } are used for lists. •Double square brackets [[ ]] are used to extract elements from lists. It takes some time to get used to these conventions, and at the beginning you will often get error messages and wrong results because you have not remembered these rules. Later, you may see that the conventions have advantages. Let us consider the conventions in more detail. ‡ Names

Mathematica is case sensitive. If a name is Sin, you cannot write sin or SIN; you must write Sin exactly. It is recommended that all names you introduce (like a, b, and c previously) begin with a small letter. If this convention is followed, then it is always clear which names are built-in and which are defined by the user. Such a distinction makes reading the Mathematica code easier; you need not remember whether a name is your own. Also, you cannot mistakenly define a symbol with the same name as a built-in command, thereby avoiding any confusion. Many built-in names consist of several words run together, such as FindMinimum, and in these cases each individual word begins with a capital letter. If you define a name consisting of several words, you can use capital letters in the middle of the name, as in randomWalk; this makes reading the name easier. Another convention is that all built-in names and words are written completely; abbreviations are not used. This can make some names long (e.g., InverseLaplaceTransform or NoncentralChiSquareDistribution), but the advantage is that such complete names are often easier to remember than abbreviated names. Some abbreviations exist, however, such as D (derivative), Det (determinant), and Tr (trace). Names may be as long as you want. Names cannot begin with a number. User-defined names are also often written in full without abbreviations [the longest I have seen is in Shaw & Tigg (1994, p. 104): NapoleonicMarchOnMoscowAndBackAgainPlot]. Let us try out an example with the capital first letter. Instead of the correct form Sin[p/2], write [email protected] ê 2D

p sinB F 2

Note that, in the command, sin remained blue, and this means that Mathematica does not know about sin. We did not get the expected result 1. We correct the command: [email protected] ê 2D

1

‡ Multiplication

Multiplication was already considered in Section 1.2.3, p. 10, but let us still try some examples: a=3

3

b=4

4

8a b, a * b, ab< 812, 12, ab<

Recall that you cannot write ab if you want a times b. If you write ab, Mathematica understands it as a variable with the name ab. Some more examples:

14

Mathematica Navigator 85 a, a5, d He + fL, Hd + eL Hf + gL, [email protected] [email protected]<

815, a5, d He + fL, Hd + eL Hf + gL, [email protected] [email protected]<

Note that with a numeric multiplier, we do not need to write a multiplication indicator such as a space or an asterisk. We can write 5a; Mathematica automatically adds a space between the terms. However, a5 is interpreted as a name. No space or asterisk is needed with parentheses either: We can write c(d+e) and (c+d)(e+f), and Mathematica adds the space. A multiplication indicator is generally not needed between complete expressions. For example, we can write Sin[x]Cos[y], and, again, Mathematica adds the space. If a multiplication occurs at the end of a line, then it is safe to use the asterisk ( *). Place the asterisk either at the end of the first line or at the beginning of the next line. If you do not use the asterisk, Mathematica understands the two rows as separate commands, if they can be interpreted as complete commands. ‡ Arguments

In traditional mathematical notation, parentheses are used for two purposes: for arguments and for grouping terms. Mathematica avoids this ambiguity by using different notation for these two purposes: square brackets for arguments and parentheses for grouping. For example, if we write, instead of the correct form Sin[p/3], what you see below, we get a wrong result: Sin Hp ê 3L

p Sin 3

Mathematica interprets the expression according to its standard rules: Sin is a variable by which we want to multiply Pi/3. Note that the parentheses are red to remind that the syntax is incorrect. Here is the correct command: [email protected] ê 3D

3 2

‡ Grouping

Be careful in entering expressions. Parentheses are sometimes easily forgotten, and the result will be incorrect. Special care is necessary with quotients and rational powers. Here are some examples of quotients: 81 ê 4 [email protected] [email protected], 1 ê H4 [email protected] [email protected], 1 ê H4 [email protected] [email protected]< :

[email protected]

1 x [email protected], 4

1 ,

4

x

4

>

x [email protected]

Thus, a/b*c in interpreted as (a/b)*c and not as a/(b*c). Here are some examples of powers: 8E ^ -1, E ^ -1 ê 2, E ^ H-1 ê 2L< 1 1 , : , ‰ 2‰

1

>



Thus, a^b/c is interpreted as (a^b)/c and not as a^(b/c). Remember to write the necessary parentheses, and if you are uncertain whether you should use parentheses or not, go ahead and use them because unnecessary parentheses are harmless. Note that if you want to square Sin[x], you can simply write Sin[x]^2. If you want to calculate the value of Sin at x^2, write Sin[x^2].

Chapter 1 • Starting

15

‡ Lists

Lists are like vectors: A list is, mathematically, an ordered set of elements. Lists are used to store data and expressions. Here is an example of a list with three elements: 86, 2 ‰, -0.587785<

c = 86, 2 E, [email protected] pD<

Curly braces are reserved for lists. Another example: d = [email protected], Pi, 2<

[email protected], p, 2<

Calculations with lists are simple because all operations are automatically done element by element: d^2 c+d

[email protected] , p2 , 4=

86 + [email protected], 2 ‰ + p, 1.41221<

Double square brackets are used to extract elements from lists. For example: [email protected]@2DD

2‰

In place of [[…]] we can also use P…T; here, P and T can be written as Â[[Â and Â]]Â.

1.4 Getting Help 1.4.1 Palettes Some palettes can help you when you are entering input for Mathematica in notebook environments. Palettes can be accessed from the Palettes menu. Below we show four palettes: AlgebraicManipulation, BasicMathInput, BasicTypesetting, and SpecialCharacters.

16

Mathematica Navigator

‡ AlgebraicManipulation

The AlgebraicManipulation palette contains such commands as Expand, Factor, and Simplify. As an example, type the following: Hf + gL ^ 6

Then select the whole expression with the mouse and click Expand in the palette. The expression is expanded. Then click Factor in the palette. The expression is now factored. In this way, whatever is currently selected in your notebook will be inserted into the position of the selection placeholder, É, that can be seen in the commands of the palette. ‡ BasicMathInput

The BasicMathInput palette contains buttons to perform some basic calculations and to input some basic symbols. Suppose you want to calculate the derivative of x sinHxL + cosHxL. First click the derivative button Ñ É, then write x, press Í, write (x Sin[x] + Cos[x]), and execute the resulting command: x Hx [email protected] + [email protected]

x [email protected]

You can also do the following: Write (x Sin[x] + Cos[x]), select the whole expression, click the derivative button, press x, and execute. For another example, suppose you want to calculate the definite integral of x sinHxL + cosHxL on

H0, 2 pL. First click the integral button ŸÑ É „ Ñ, then write 0, press Í, write 2, click p on the palette, press Ñ

Í, write (x Sin[x] + Cos[x]), press Í, write x, and execute: ‡

2p

Hx [email protected] + [email protected] „ x

-2 p

0

You can also do this the other way: Write first (x Sin[x] + Cos[x]), select the whole expression, click the integral button, and fill the limits and the integration variable with the help of Í. This palette also contains buttons for powers, fractions, roots, sums, products, 22 matrices, and part extraction. Also included are the four basic symbols p (= 3.14159...), ‰ (=2.71828...), Â ( =

-1 ), and ¶

(=infinity). ‡ BasicTypesetting

The BasicTypesetting palette contains many mathematical characters and constructs, useful especially in writing mathematical text with Mathematica. Mathematica as a writing environment is considered in Chapter 3. ‡ SpecialCharacters

The SpecialCharacters palette contains all of the characters that can be entered into Mathematica. The characters are in groups such as Greek letters, script letters, general operators, and arrows. Just put the cursor in the place in your notebook where you want to add a character, choose a suitable group from the palette, and click on a character. The selected character can now be seen in an enlarged form. Then click Insert.

Chapter 1 • Starting

17

1.4.2 On-line Documentation ‡ Documentation Center

Mathematica 6 used in notebook environments incorporates an excellent help system called the Documentation Center. Go to the Help menu and choose Documentation Center (or press ˜ÎF1Ï in Windows or the Help key in Macintosh). The home page of the center appears:

In the home page, the material about Mathematica is classified into seven topics such as Core Language and Visualization and Graphics. Inside each topic, we have a list of narrower topics; they are hyperlinks to the corresponding documents. In these documents, we have classified lists of suitable commands associated with the topic in question; such documents are called guide documents. Each command is again a hyperlink to a document in which the command is explained in detail; such documents are called reference documents. The guide and reference documents also have hyperlinks to documents explaining the use of the commands; such documents are called tutorial documents. Each document also has an input field for searching a topic. The Documentation Center can also be used as follows. In your notebook (not in the Documentation Center), type a command such as Solve, leave the cursor at the end of the word, and press the F1 key (in Macintosh the Help key can also be pressed) or choose Help @ Find Selected Function. The page explaining the command appears. Note that you can have multiple help windows open. Indeed, every time you choose Help @ Documentation Center a new help window opens. The Documentation Center includes the equivalent of 50,000 pages of material, with more than 100,000 examples and more than 150,000 links. The center contains 345 guide documents, 655 tutorial documents, and thousands of reference documents (as of Mathematica 6.0.2). The examples in the reference documents contain commands that have already been executed. You can also execute them anew and you can add new calculations. Note that all these calculations do not have any effect in your own notebook. For example, a package may have been loaded in a reference document. If you want to use the same package in your own document, you have to load the package in your document.

18

Mathematica Navigator

Note that the packages of Mathematica also have guide, tutorial, and reference documents; they can be accessed from the guide documents of the packages. Hyperlinks to these guide documents are given in Section 4.1.1, p. 94. ‡ Function Navigator and Virtual Book

In addition to Documentation Center, Mathematica also contains two useful views of information: Function Navigator and Virtual Book (new in Mathematica 6.0.2). Below we show the Documentation Center, the Function Navigator, and the Virtual Book, all opened to show functions or topics in dynamic interactivity.

The Function Navigator and Virtual Book can be accessed from Help @ Function Navigator and Help @ Virtual Book. Actually, we only have one window that shows either the Function Navigator or the Virtual Book; the choice can be made at the top of the window. The main topics accessible in these windows are classified similarly as the topics in the Documentation Center. A guide document shown by Documentation Center gives a short introduction to the topic and lists of commands with short descriptions for main commands; the page also has links to other guide pages (e.g., Options & Styling) that contain more complete lists of commands. The commands are links to the corresponding reference documents. The Function Navigator centers to give lists of commands classified to several topics; each command is a link to the corresponding reference document. So, the Function Navigator can be used to quickly show lists of commands and to show reference documents. The Virtual Book contains links to tutorial documents. The tutorials are comprehensive enough to constitute a virtual book about Mathematica. Users of previous versions of Mathematica have read The Mathematica Book, the complete manual of Mathematica, but in version 6 we no longer have the manual as a printed book. Instead, all documentation is now on-line. This has the advantages that there is no limit on the amount of material and the material can be continuously updated.

Chapter 1 • Starting

19

In addition to the Virtual Book, we mention the following guide and tutorial documents: • guideêNewIn60AlphabeticalListing • guideêSummaryOfNewFeaturesIn60 • guideêListingOfNamedCharacters • guideêListingOfAllFormats • tutorialêTraditionalFormReferenceInformation • tutorialêIncompatibleChanges See also the following web documents: Overview of Mathematica, Wolfram Mathematica 6 Comparative Analyses, and The Wolfram Technology Guide.

Wolfram Mathematica 6,

‡ Finding Information

With the Documentation Center, Function Navigator, and Virtual Book, finding suitable information is efficient and easy. The input field in the Documentation Center can also be used to search information about a given topic. The suitable document may open directly or, if there are several suitable documents, we get a list of links. From this list, we often easily find a suitable document. If we would like to get directly to a document in the Documentation Center, we have to write its name. Generally, the names of the documents begin with ref, guide, or tutorial. Examples of names of documents are as follows: Kernel: ref/Integrate: detailed information about Integrate guide/Calculus: lists of commands related to calculus tutorial/IndefiniteIntegrals: a tutorial of indefinite integration Packages: LinearRegression/ref/Regress: detailed information about Regress from the LinearRegression package LinearRegression/guide/LinearRegressionPackage: lists of commands from the package LinearRegression/tutorial/LinearRegression: a tutorial of the package Notebooks: ref/character/Rule: detailed information about the Ø character guide/MathematicalTypesetting: lists of commands related to mathematical typesetting tutorial/TwoDimensionalExpressionInputOverview: a tutorial of entering 2D inputs Formats: ref/format/EPS: detailed information about the EPS format guide/ListingOfAllFormats: a list of all formats tutorial/ImportingAndExportingData: a tutorial of importing and exporting data Messages: ref/message/General/plln: detailed information about the General::plln message guide/Messages: a list of commands related to messages tutorial/Messages: a tutorial of messages Menus: ref/menuitem/New: explanation of the File @ New menu command guide/FileMenu: a list of the File menu items In the way, the documents of the Documentation Center are located at Mathematica 6 @ Documentation @ English @ System. There, we have folders ReferencePages, Guides, and Tutorials.

20

Mathematica Navigator

‡ Automatic Updates

Mathematica has an automated way to update the information in the Documentation Center. Information in the center is in the form of so-called paclets. Often they are documentation notebooks, but they may also be data. Wolfram Research has a paclet server containing the latest information. Mathematica in your computer weekly contacts this server and checks which paclets have updated documentation (the updates are not loaded at this stage, however). In this way, Mathematica maintains local indices of paclets in your computer. Now, when you ask information about, for example, Solve, Mathematica checks from the indices whether new information is available. If yes, Mathematica contacts the paclet server, loads the update, and then shows this latest information to you. If no, then an update is not needed and Mathematica shows the current information available in your computer. Mathematica’s use of the Internet can be controlled from Help @ Internet Connectivity…. Note that some data collection functions may not work without an Internet connection. ‡ Introductions

If you are a new user of Mathematica and would like to study the basics of Mathematica 6, look at the following documents: • Help @ Startup Palette: the First Five Minutes with Mathematica button • Help @ Virtual Book: the Introduction item If you are an old user of Mathematica and would like to study the new features in Mathematica 6, look at the following documents: • Help @ Startup Palette: the What’s New in 6 link to Wolfram’s website • Help @ Documentation Center: the New in 6 links in the home page • Help @ Documentation Center: the guideêSummaryOfNewFeaturesIn60 document • Help @ Documentation Center: the guideêNewIn60AlphabeticalListing document • Help @ Function Navigator: the New In 6 item The Preface also contains information about the new functionality of Mathematica 6 and about obsolete properties. ‡ Help Browser

The home page of the Documentation Center has a link Installed Add-Ons. By clicking this link we get a list of add-ons that have been installed into the so-called Help Browser of Mathematica. Prior to version 6, the Help Browser was the main help system. In version 6, the main help system is the Documentation Center, whereas the Help Browser only contains help material of add-ons of Mathematica. For example, the material on the CD-ROM of this book can be installed into the Help Browser, so that the book can be easily browsed within Mathematica.

1.4.3 Other Help ‡ The Question Mark

With the question mark (?) and asterisk (*), we can get lists of names containing certain characters. Suppose you are interested in finding a minimum of a function. Perhaps such a command has Mini in its name, and so we ask Mathematica to give a list of all names containing Mini:

Chapter 1 • Starting

21

? *Mini*

System` DigitBlockMinimum

MinimalPolynomial

FindMinimum

Minimize

NMinimize

Now we can ask for information about these commands by clicking the names of the commands. For example, if we click Minimize, we get the following short information: [email protected] f , 8x, y, …
By clicking the à link, we get Documentation Center to open, and the information about Minimize is displayed. Another way to use the question mark is to directly ask information about a particular command: ? Minimize [email protected] f , 8x, y, …
The double question mark gives the same information as the single question mark and, in addition, information about attributes and options. ‡ Completing Names and Making Templates

Mathematica has quite long names for some commands, but in notebook environments you can let Mathematica do some of the typing work. Use palettes or the following technique. Suppose we want to write the command InterpolatingPolynomial. We first write, for example, Interpo, and then press ‚Î k Ï (or ÌÎ k Ï on a Macintosh); this is the same as choosing Complete

Selection in the Edit menu. We get the following list:

Here are all the commands beginning with Interpo. From the list, we can choose the one we want by clicking with the mouse or by highlighting the appropriate command with the arrow keys and then pressing Á. Interpo is then automatically completed according to your choice.

22

Mathematica Navigator

Now that we have the complete name of the command InterpolatingPolynomial, we can press ˜÷‚Î k Ï (or ˜÷ÌÎ k Ï on a Macintosh); this is the same as choosing Make Template from the Edit menu. We get a template for the command: [email protected] f1 , f2 , …<, xD

This is useful if we do not remember the syntax of a command. Now we can replace 8 f1 , f2 , …< with our data and x with our variable and then execute the command. If the name of the command is uniquely determined by the first letters we have written,then ‚Î k Ï will complete the name directly, and ˜÷‚Î k Ï will complete the nameand make a template for the command. Try typing InterpolatingP and then pressing ‚Î k Ï or ˜÷‚Î k Ï. ‡ Syntax Coloring

In writing commands, Mathematica uses colors to indicate various aspects of syntax. To see the colors explained, open Preferences from a menu (in a Macintosh, this menu command is in the Mathematica menu) and go to Appearance @ Syntax Coloring. For example, variables for which we have not given a value are blue, syntax errors purple, emphasized syntax errors red on a yellow background, unrecognized options red, and arguments of functions green. Missing arguments are represented by a red Ô symbol. The colors help in getting the commands into a correct form. From Help @ Why the Coloring… we can see real-time explanations of the colors as we write an input. ‡ Balancing Paired Characters

When writing commands and programs with Mathematica, you may use many parentheses (), brackets [ ], and curly braces { }. It may be difficult to see whether they are correctly balanced. Mathematica helps with this as follows: Unbalanced characters are shown in purple, and each time you write ), ], or }, Mathematica highlights the corresponding (, [, or { for a short time. You can also use Check Balance from the Edit menu or press ˜÷‚Î b Ï (or ˜÷ÌÎ b Ï on a Macintosh). Place the cursor somewhere in the command and then press the previously mentioned key combination. The smallest balanced part containing the cursor will be highlighted; if a correctly balanced part cannot be found, nothing happens. In the Edit menu, we also have the Extend Selection command (‚÷Î . Ï). Put the cursor somewhere in a command. By repeatedly pressing ‚÷Î . Ï, larger and larger subexpressions are selected. Triple-click on a function to select the function and its arguments. ‡ Help from Wolfram Research

Help can also be found at the website http://support.wolfram.com of Wolfram Research. To display the version of Mathematica you are using (and thus find the appropriate information), execute the command $Version. Execute SystemInformation[] to get a detailed summary of your Mathematica installation.

1.5 Editing ‡ Correcting

In notebooks, you can use all the usual editing methods familiar from word processors. Look at the Edit menu for editing commands. Note especially that you can edit all old inputs and execute them anew. To recalculate an input, simply place the cursor anywhere in the command and then execute the command.

Chapter 1 • Starting

23

In particular, if an input resulted in errors, you do not need to retype the input; simply correct the old input by means of standard editing and then execute the input again. Note also that the input and output numbers are assigned in the order of execution and not according to the physical order of the commands in the notebook. ‡ Using Cells

You have probably noted the brackets at the right side of the Mathematica window. They indicate cells. An input is in a cell, the result is in another cell, and these two cells together form a higher-level cell. A new input cell is automatically created when you start typing after a command is executed. A notebook is a structured document that is organized into a sequence of cells. You can insert new cells between old cells. Simply place the cursor between two cells so that the cursor becomes horizontal, and then click with the mouse and start typing. In this way, you can insert new calculations among old ones. The cells are handy for moving a part of a notebook to another place: Just click on the cell bracket so that it becomes black, and then cut or copy the cell and paste it to a new location. You can select several cells by dragging with the mouse over the cell brackets. You can copy material from one notebook to another notebook with the usual copy-and-paste techniques. Copying is easy to do by selecting cells. If you want to re-execute several cells, select the cell brackets and then execute them in the standard way. Double-clicking a cell bracket closes the cells inside it so that only the first cell is visible. In this way, you get a short outline of your notebook. Double-clicking the cell bracket of a closed cell opens the cell again. Double-clicking an input cell hides the output cell, and double-clicking an output cell hides the input cell. ‡ Each Command into Its Own Cell

Mathematica is an interactive calculator that is designed such that we can easily proceed step by step: We execute one command and then proceed to the next command. A common bad habit is to write several commands in one cell and then execute all the commands at the same time. When this happens, the connection between inputs and the corresponding outputs becomes obscured. For example, f = x [email protected] [email protected], xD [email protected], xD x [email protected] -x [email protected] + [email protected] x [email protected] + [email protected]

Here we put three commands into one cell. The outputs are shown one after another. This is not clear. In addition, if one of the commands contains an error, we have to execute all the commands anew instead of only re-executing the corrected command. So, write each command in its own cell: f = x [email protected] x [email protected] [email protected], xD -x [email protected] + [email protected] [email protected], xD x [email protected] + [email protected]

24

Mathematica Navigator

As previously stated, a new input cell is automatically created when you start typing after a command is executed. If you want to write several commands before you execute any of them, create a new cell for each command as follows: Write a command, press the down arrow key (), and start writing the next command. (Instead of the arrow key, you can also place the cursor below the last command so that the cursor becomes horizontal, click with the mouse, and start typing the next command.) Note that if a calculation takes some time, you need not be idle. You can write (but not execute) new commands so that they are ready when the present command has been executed. You can also edit the notebook in any way you like while you await the execution of a command. ‡ Editing Inputs

Sometimes you want to slightly modify an old input and then execute it again. You have several options. First, you can directly edit the old input and then re-execute it, as previously explained. Second, you can select an old input or a part of it with the mouse, copy the selection, paste it to a new location, edit, and execute. A whole input can be selected by clicking the cell bracket, and the cell can then be copied and pasted. Third, if the input you want to modify is the last input, you can get a copy of it by pressing ‚Î l Ï (or ÌÎl Ï on a Macintosh); this is the same as choosing Input from Above in the Insert menu. Mathematica divides long inputs automatically into several lines. However, you can also press the Return key (Á) here and there to make long code easier to read. You can also execute a part of an input. Select with the mouse the part you want to execute, and then press ‡÷Á or Ì÷Á (this corresponds to Evaluation @ Evaluate in Place). Only the selected part is then executed. ‡ Editing Outputs

You also have access to the results Mathematica writes. For example, you can copy a result or a part of it, paste the copy to a new cell, edit the new command, and then execute it. If you want to edit the result of the last command, you can get a copy of the result by pressing ˜÷‚Î l Ï (or ˜÷ÌÎ l Ï on a Macintosh); this is the same as choosing Output from Above in the Insert menu. ‡ Opening a Saved Notebook

Note that if you open a saved notebook and continue calculations, you cannot directly use any results in the saved document. You have to recalculate all the commands with the results you need in your new session. Suppose, for example, that the saved notebook contains the result of int = Integrate[Sqrt[x] Sin[x], x]. When you open the notebook, int has no value. If you need the value of int in your new session, you have to execute anew the integrating command. ‡ Writing a Document with Mathematica

You can write a whole document with Mathematica by calculating, plotting, and adding text comments to the results. To modify the look of the document, you can use styles and style sheets. These are considered in detail in Chapter 3. After you have written your document with Mathematica, check spelling by placing the cursor at the beginning of the document and then choosing Edit @ Check Spelling…. English is built into Mathematica, but you can buy dictionaries of other languages from Wolfram Research.

2 Sightseeing Introduction 25 2.1 Graphics 26 2.1.1 Graphics for Functions 26 Plot, Show, GraphicsRow, Plot3D, ContourPlot, ListPlot, etc. 2.1.2 Graphics for Data 29 ListPlot, ListLinePlot 2.1.3 Manipulations 30 Manipulate 2.2 Expressions 31 2.2.1 Numbers and Expressions 31 N, RandomReal, /., Simplify, FullSimplify, Factor, Expand, etc. 2.2.2 Lists and Tables 34 MatrixForm, TableForm, Grid, Row, Total, Tally, Range, Table, Map, etc. 2.2.3 Functions and Programs 39 Module 2.3 Mathematics 40 2.3.1 Differential and Integral Calculus 40 D, Series, Limit, Integrate, NIntegrate, Sum 2.3.2 Matrices 42 Transpose, Det, Inverse, Eigenvalues 2.3.3 Equations 43 Solve, NSolve, FindRoot 2.3.4 Optimization 45 Minimize, NMinimize, FindMinimum, etc. 2.3.5 Interpolation and Approximation 46 Interpolation, Fit 2.3.6 Differential Equations 48 DSolve, NDSolve

Introduction The relationship between pure and applied mathematics is based on trust and understanding: The pure mathematicians don’t trust the applied mathematicians, and the applied mathematicians don’t understand the pure mathematicians. Welcome all mathematicians, pure and applied, and everyone else, too, to a quick sightseeing tour through the vast and wonderful Mathematica factory, which produces graphics, eigenvalues, integrals, and so much more. We will visit the three main divisions of the factory: Graphics, Expressions, and Mathematics. In each division, we will show you only the most important or most basic machines (a total of approximately 60, leaving more than 3000 that are not shown). We will introduce each machine only briefly, but we encourage you to spend more time investigating and experimenting (at your own risk, of course; use a helmet, because every erroneous input is thrown out of the machine). Later, we will explain all this and much more in detail, but the knowledge you get during this sightseeing tour may suffice for awhile. In fact, this short tour gives you snapshots of Chapters 5 through 28. Please note that what you will see in this chapter is not anything spectacular but only some very basic facts. Later, we will show you some much more impressive results.

26

Mathematica Navigator

2.1 Graphics 2.1.1 Graphics for Functions ‡ Graphics for 2D Functions Plot[f, {x, a, b}] Plot f when x takes on values from a to b Plot[{f1, f2}, {x, a, b}] Plot f1 and f2 in the same figure Show[p1, p2] Show figures p1 and p2 superimposed

We plot two functions in the same figure (recall that p can be written as Pi or as ÂpÂ): [email protected]@xD, [email protected]<, 8x, 0, 2 p
2

3

4

5

6

-0.5 -1.0

Note that the curves automatically have different colors. We can also first plot the two figures separately: p1 = [email protected]@xD, 8x, 0, 2 p
2

3

4

5

6

-0.5 -1.0

p2 = [email protected]@xD, 8x, 0, 2 p
2

3

4

5

6

-0.5 -1.0

Then we can combine them (now the curves have the same color): [email protected], p2D 1.0 0.5 1

2

3

4

5

-0.5 -1.0

We could also do as follows:

6

Chapter 2 • Sightseeing

27

[email protected]@[email protected], 8x, 0, 2 p
2

3

4

5

6

-0.5 -1.0

‡ Arranging Graphics {p1, p2} (Ÿ6) Show figures p1 and p2 side by side in a list form Row[{p1, p2}] (Ÿ6) Show figures side by side in two graphics GraphicsRow[{p1, p2}] (Ÿ6) Show figures side by side in one graphic GraphicsGrid[{{p1, p2}, {p3, p4}}] (Ÿ6) Show figures as an array

The figures can be placed side by side: 8p1, p2<

:

1.0

1.0

0.5

0.5 1

2

3

4

5

6

,

1

-0.5

-0.5

-1.0

-1.0

2

3

4

5

6

>

Here, note the list structure {…, …} of the output. In the following way we get the two figures side by side without the list structure: [email protected], p2
1.0

0.5

0.5 1

2

3

4

5

6

1

-0.5

-0.5

-1.0

-1.0

2

3

4

5

6

This output still contains two separate plots. If we like to get one figure containing the two plots, we can write as follows: [email protected], p2<, ImageSize Ø 260D 1.0

1.0

0.5

0.5 1

2

3

4

5

6

1

-0.5

-0.5

-1.0

-1.0

2

3

4

5

6

Here we used the ImageSize option to enlarge the figure (the arrow Ø can be written by pressing the hyphen and greater-than keys in turn; Mathematica will then replace them with a genuine arrow).

28

Mathematica Navigator

‡ Showing the Whole Function

We can enter the expression to be plotted directly in the plotting command, as we have done thus far, but we can also first give a name to the expression: f = x ^ 2 [email protected] [email protected];

To save space, in this book we often suppress the display of outputs by ending the command with the semicolon. Then, plot the function: [email protected], 8x, 0, 14
-0.1

2

4

6

8

10

12

14

-0.2

In this example, we do not see the whole function in the given interval. Indeed, sometimes Mathematica cuts a part of the figure out in order to give you a closer look at the more interesting parts of the curve. You can control the range of y values by using the PlotRange option. If you want to see the whole function, give the option PlotRange Ø All: [email protected], 8x, 0, 14<, PlotRange Ø AllD 0.4 0.2 2

4

6

8

10

12

14

-0.2

‡ Suppressing the Display

With the semicolon, we can also suppress the display of graphics; p1 = [email protected]@xD, 8x, 0, 2 p
The plots were prepared, but they were not shown. The plots can then be superimposed or shown side by side: [email protected], p2D 1.0 0.5 1

2

3

4

5

6

-0.5 -1.0

[email protected], p2<, ImageSize Ø 230D 1.0

1.0

0.5

0.5 1

2

3

4

5

6

1

-0.5

-0.5

-1.0

-1.0

2

3

4

5

6

Chapter 2 • Sightseeing

29

‡ Graphics for 3D Functions Plot3D[f, {x, a, b}, {y, c, d}] Plot f as a surface ContourPlot[f, {x, a, b}, {y, c, d}] Plot f as contours DensityPlot[f, {x, a, b}, {y, c, d}] Plot f as a density plot

We plot a function of two variables as a surface, contour, and density plot: f = [email protected] ^ 2D [email protected]@yDD;

[email protected], 8x, 0, 3<, 8y, 0, 4
:

,

,

>

On the contours in a contour plot, the function takes on a constant value; dark areas are lower than light areas. By moving the mouse pointer over the contour plot (without pressing the mouse button), we can see the values of the contours. In the density plot, dark areas are also lower than light areas.

2.1.2 Graphics for Data ListPlot[data] Plot data as points ListPlot[data, Filling Ø Axis] (Ÿ6) Plot data as points and vertical lines ListLinePlot[data] (Ÿ6) Plot data as joining lines ListLinePlot[data, Mesh Ø All] (Ÿ6) Plot data as joining lines and points

The data are given in either of the following forms: 8y1, y2, ..., yn<

88x1, y1<, 8x2, y2<, ..., 8xn, yn<<

In the former case, the x values are automatically 1, 2, 3, …; in the latter case, we give explicit x values. Here are some data and three plots: data = 880, 5<, 81, 7<, 82, 8<, 83, 7<, 84, 9<, 85, 8<, 86, 6<, 87, 5<, 88, 5<, 89, 4<, 810, 5<, 811, 3<, 812, 0<, 813, 1<<;

30

Mathematica Navigator [email protected]@dataD, [email protected], Filling Ø AxisD<, [email protected], [email protected], Mesh Ø AllD<<, ImageSize Ø 300D

2.1.3 Manipulations To create an interface enabling the interactive choice of the value of the parameter u with a slider and showing the corresponding value of expr: Manipulate[expr, {u, umin , umax }] (Ÿ6) u can have any value between umin and umax Manipulate[expr, {u, umin , umax , du}] u can have any value between umin and umax in steps of du

With a manipulation we can investigate how an expression changes when one or more parameters change. The main use of manipulations is to study plots, but other expressions can also be manipulated. Here are two examples. In the first manipulation, parameters a and b take on values from 0 to 2: [email protected]@[email protected] xD [email protected] xD, 8x, 0, 2 p<, PlotRange Ø 8-1.05, 1.05<, ImageSize Ø 200D, 8a, 0, 2<, 8b, 0, 2
The sliders can be moved with the mouse so that we can see in real time how the plot changes. In the second manipulation, the parameter n takes on values from 0 to 6 in steps of 1~that is, the discrete values 0, 1, 2, …, 6:

Chapter 2 • Sightseeing

31

[email protected] [email protected]@n xD, 8x, 0, 2 p<, PlotRange Ø 8-0.25, 1.05<, ImageSize Ø 200D, 8n, 0, 6, 1
2.2 Expressions 2.2.1 Numbers and Expressions ‡ Numbers N[expr] or expr//N Calculate a decimal value of expr N[expr, n] Calculate a decimal value of expr to n-digit precision

Here is a decimal value for p: p êê N

3.14159

Now we ask for a decimal value to 30-digit precision: [email protected], 30D

3.14159265358979323846264338328

RandomReal[{a, b}, n] (Ÿ6) n random numbers from the interval (a, b) RandomInteger[{k, l}, n] (Ÿ6) n random numbers from the integers from k to l SeedRandom[n] Reseed the random number generator with the integer n

Random numbers can be used in simulating various phenomena. Here are some uniform random numbers: 80.335378, 0.0610635, 0.892345, 0.0844273, 0.748569, 0.451667, 0.704084< [email protected], 1<, 7D

Then we simulate die tossing: 85, 3, 5, 1, 2, 1, 1, 3, 1, 1, 4, 6, 3, 1, 4, 5, 5, 2, 4, 4, 5, 2, 5, 3<

[email protected]; [email protected], 6<, 24D

Bad luck as usual: only one 6, although four were expected.

32

Mathematica Navigator

‡ Calculating the Value of an Expression x = a Give x the value a expr Show the value of expr when x has the value a

If you want to calculate the value of an expression for a certain value of a variable, one possibility is to explicitly give the value for the variable and then ask the value of the expression: expr = [email protected] [email protected]; x = p ê 6;

3 expr

This method has the drawback that from now on x has the value p ê 6 in all expressions, and this may give unintended results. For example, if you now try to calculate the derivative of the expression, you get an error message: 4

[email protected], xD General::ivar :

p

p 6

is not a valid variable. à

3

Mathematica could not calculate the derivative with respect to a constant p ê 6. So, if you give values for variables, remember to remove the values when you no longer need them: 6

4

x =. expr /. x Ø a Replace x by a in expr

The arrow can be written as -> (Mathematica automatically replaces these characters by a genuine arrow Ø). This is the recommended method to calculate the value of an expression for a value of a variable. For example: expr ê. x Ø p ê 6

3 4

This is a very important technique. Here, x Ø p/6 is a transformation rule. It can be applied to any expression by preceding the transformation rule with /. . Note that now x has no value: x

x

Another example: [email protected] ê. x Ø 1

p 2

‡ Manipulating Expressions Simplify[expr] Simplify expr FullSimplify[expr] Simplify expr thoroughly Factor[expr] Factor expr Expand[expr] Expand expr Apart[expr] Give the partial fraction expansion of expr

Chapter 2 • Sightseeing

33

Note that these commands can also be used in the following way: expr // Simplify. For example, a = H1 + xL ^ 2 + H1 + xL H2 + xL

a êê Simplify a êê Factor

a êê Expand

H1 + xL2 +H1 + xL H2 + xL

3 +5 x +2 x2

H1 + xL H3 + 2 xL 3 +5 x +2 x2

FullSimplify is often good for simplifying special functions. In the following example, Simplify does not work, but FullSimplify does: n ! ê Hn - 1L ! êê Simplify

n!

H-1 + nL ! n ! ê Hn - 1L ! êê FullSimplify n

We calculate a partial fraction expansion:

H1 + x + x ^ 2 - x ^ 3L ê Hx + 2L ^ 2 êê Apart

5-x+

11

H2 + xL

2

15 2+x

‡ Function Application f[expr] Standard function application expr // f Postfix function application f @ expr Prefix function application

Thus far, we have seen that we can write N[expr] or Simplify[expr] but we can also write expr//N and expr//Simplify. The use of the square brackets is the standard way to apply functions.

The use of // is called a postfix function application. We also have a prefix function application: N@expr, Simplify@expr. In the following example, we use all three function applications: [email protected], p êê N, N ü p<

83.14159, 3.14159, 3.14159<

The standard notation also applies for functions with several arguments: f[x, y]. The postfix and prefix notations can only be used for functions with one argument. ‡ Some Display Techniques

Sometimes we need not see the result of a computation. For example, we already know the result for certain, the result is so large an expression that it is useless to see it, or it takes too much time to have it displayed on the screen. We can prohibit displaying the result by ending the command with a semicolon (;). expr; Calculate the value of expr but do not display the result

We do not want to see 100! (a number with 158 digits): a = 100 !; a ê 99 !

100

We can execute several commands at the same time using the semicolon:

34

Mathematica Navigator

expr1; expr2; expr3 Calculate the expressions; display the last result expr1; expr2; expr3; Calculate the expressions; do not display anything

We calculate other factorials and display only the final result: b = 97 !; c = 3 !; a ê Hb cL

161 700

If you want to display the values of all expressions, you can place the expressions in a list with curly braces: {expr1, expr2, expr3} Calculate the expressions; display all values [email protected] ê 4D, [email protected] ê 5D, [email protected] ê 6D, [email protected] ê 7D< :

1

5 ,

2 % êê N

-

5

p , SinB F> 2 7 1

,

80.707107, 0.587785, 0.5, 0.433884< 8

8

For long expressions, it often suffices to see only some parts. This can be done with Short: Short[expr] Give expr in a shortened form Short[expr, c] Give expr in a shortened form having length c

We generate 50 uniform random numbers but show only a few of them: t = [email protected], 1<, 50D; 80.214152, á48à, 0.130847< [email protected]

80.214152, 0.613783, 0.767945, á44à, 0.011151, 0.44259, 0.130847< [email protected], 4D

In the first case 48 values and in the latter case 44 values are not shown. (To find an appropriate length, such as 4, for the expression may take some experimenting.) Before we continue, we clear the values of a, b, c, and t. We could write a=.; b=.; c=.; t=., but a more convenient way is the following: [email protected], b, c, tD

2.2.2 Lists and Tables ‡ Lists {a, b, c} A 1D list list[[i]] ith part of list Length[list] Number of elements in list Sort[list] Sort the elements of list into canonical order {{a, b, c, d}, {e, f, g, h}} A 2D list list[[i, j]] (i, j)th part of list

In place of [[…]] we can also use P…T; here, P and T can be written as Â[[Â and Â]]Â.

Chapter 2 • Sightseeing

35

Lists are very basic objects in Mathematica; you will use them all the time. Vectors and matrices are in fact lists, and in many other computations you need lists. Lists can have as many elements as you want them to have (an empty list is {}). Lists with lists as elements are 2D, 3D, and higher-dimensional lists. We define two lists: a = 8x, y, z, v<;

b = 883, 2, 5, 4<, 84, 1, 6, 2<, 83, 1, 1, 6<<;

Picking a part of a list is easy: [email protected]@3DD [email protected]@2DD

z

84, 1, 6, 2<

[email protected]@2, 3DD

6

Here are the lengths of the lists: [email protected]

4

[email protected]

3

We try Sort: 82, 3, 4, p, P, q, r<

[email protected], 4, P, 2, q, p, 3
Note that calculations with lists are automatically done element by element: 2 83, 2, 5, 4<

83, 2, 5, 4< ^ 2

86, 4, 10, 8<

89, 4, 25, 16<

83, 2, 5, 4< + 84, 1, 6, 2<

87, 3, 11, 6<

‡ Tables MatrixForm[m] Display matrix m in a 2D matrix form TableForm[m] Display m in a 2D tabular form Grid[m] (Ÿ6) Display m in a 2D tabular form Row[v] (Ÿ6) Form a row from a list v

Matrices can be displayed handily with MatrixForm: b êê MatrixForm 3 2 5 4 4 1 6 2 3 1 1 6 TableForm prints a table: b êê TableForm 3 2 5 4 4 1 6 2 3 1 1 6 Grid also prints a table:

36

Mathematica Navigator b êê Grid 3 2 5 4 4 1 6 2 3 1 1 6

As we will see in Chapter 15, with Grid we can form advanced tables. With Row we can put elements side by side: [email protected]"1000th prime is ", [email protected]
We simulate the tossing of a die 20 times: c = [email protected], 6<, 20D

84, 4, 3, 3, 2, 4, 6, 4, 1, 5, 3, 1, 6, 5, 2, 4, 1, 2, 3, 1<

Calculate the sum, mean, (unbiased) variance, and standard deviation:

[email protected], [email protected], [email protected], [email protected]< êê N

864., 3.2, 2.58947, 1.60918<

The cumulative sums are as follows: 84, 8, 11, 14, 16, 20, 26, 30, 31, 36, 39, 40, 46, 51, 53, 57, 58, 60, 63, 64< [email protected]

Here are the frequencies: [email protected] êê Sort

881, 4<, 82, 3<, 83, 4<, 84, 5<, 85, 2<, 86, 2<< ‡ Forming Lists Range[m] Form the list {1, 2, …, m} Range[m, n] Form the list {m, m + 1, …, n} Range[m, n, d] Form the list {m, m + d, m + 2 d, …, n}

With Range, we can easily form equally spaced numbers: [email protected]

81, 2, 3, 4, 5, 6<

[email protected], 6D

80, 1, 2, 3, 4, 5, 6<

[email protected], 7, 2D

80, 2, 4, 6<

Table[expr, {i, a, b}] Form a list of values of expr when i takes on values from a to b (in steps

of 1) Table[expr, {i, a, b}, {j, c, d}] Index i takes on values from a to b and, for each i, j takes on

values from c to d

Chapter 2 • Sightseeing

37

Table is one of the most useful commands in Mathematica. It forms a list from a general rule. Iteration specification of the form {i, a, b} is most common, but other forms can also be used: {n} Form a list from n values of expr {i, b} Index i has values from 1 to b (in steps of 1) {i, a, b} Index i has values from a to b (in steps of 1) {i, a, b, d} Index i has values from a to b in steps of d

As can be seen, if the starting value of i is 1, it can be left out (but it can also be written), and if the step size is 1, it, too, can be left out. For example, [email protected], 810
80, 0, 0, 0, 0, 0, 0, 0, 0, 0< [email protected] !, 8n, 10
81, 2, 6, 24, 120, 720, 5040, 40 320, 362 880, 3 628 800< [email protected]@n p ê 6D, 8n, 0, 6
1

3 3 1 , , 1, , , 0> 2 2 2 2 [email protected]@xD, 8x, 0., 3., 0.5
81., 1.64872, 2.71828, 4.48169, 7.38906, 12.1825, 20.0855< [email protected] ê Hi + j - 1L, 8i, 4<, 8j, 4
1

1 ,

2

3

1 1 1 1 1 1 1 1 1 1 1 1 >, : , , , >, : , , , >, : , , , >> 4 2 3 4 5 3 4 5 6 4 5 6 7 1

,

Often it is useful to make pairs of the value of the index and the corresponding value of the expression: [email protected], [email protected]<, 8x, 0., 3.
880., 1.<, 81., 2.71828<, 82., 7.38906<, 83., 20.0855<<

In the following example, we study the recursion formula xi-1 = 3.7 xi I1 - xi M, i = 0, 1, 2, …. We start from x0 = 0.5 and do 200 iterations:

x = 0.5; t = [email protected] = 3.7 x H1 - xL, 8200
[email protected], AspectRatio Ø 0.4, PlotRange Ø 8-0.05, 1.05<, ImageSize Ø 300D 1.0 0.8 0.6 0.4 0.2

50

[email protected], b, c, f, x, tD

100

150

200

38

Mathematica Navigator

‡ Advanced List Manipulation

Sometimes we want to tabulate an expression for such irregular values of a variable that cannot be formed by an iteration specification; instead, we have the values of the variable as a list. Table can also be used in such cases, although Map is an alternative. Map can also be replaced with /@: Table[f[x], {x, {a, b, c}}] (Ÿ6) Calculate {f[a], f[b], f[c]} Map[f[#]&, {a, b, c}] Calculate {f[a], f[b], f[c]} f[#] & /@ {a, b, c} Calculate {f[a], f[b], f[c]}

Examples:

[email protected]@xD, 8x, 8a, b, c<
[email protected], [email protected], [email protected]<

[email protected], [email protected], [email protected]<

[email protected]ÒD & êü 8a, b, c<

Other examples: [email protected] ^ 2, 8x, 8a, b, c<
Ò ^ 2 & êü 8a, b, c<

[email protected], [email protected], [email protected]<

9a2 , b2 , c2 =

9a2 , b2 , c2 =

9a2 , b2 , c2 =

Note that the following is the easiest way to form the squares of the elements of a list: 9a2 , b2 , c2 =

8a, b, c< ^ 2

Map or /@ is one of the most useful commands for manipulating lists. In this book, we use Map extensively. With Map we can map each element of a given list with a given function. The effect of Map is that each element of the list is substituted in turn for #, and a list is formed from the results. The function is given in a special form having the name pure function. In such a function, the argument is expressed as #, and at the end of the function we have &.

Next, we tabulate values of the sin function: [email protected]Ò p ê 6D & êü 81, 2, 4, 6<

1 : , 2

3

3 ,

, 0>

The result is the value of sinHn p ê 6L for n = 1, 2, 4, 6. Recall the b we defined previously: 2

2

b = 883, 2, 5, 4<, 84, 1, 6, 2<, 83, 1, 1, 6<<;

Now we find the maximum element of each list of b: [email protected]ÒD & êü b

85, 6, 6<

If the function to be mapped is a single built-in command with one argument (e.g., Max), it suffices to write the name of the function (i.e., we need not write # and &). Therefore, we can simply write the following: Max êü b

b =.

85, 6, 6<

Chapter 2 • Sightseeing

39

2.2.3 Functions and Programs ‡ Functions f[x_] := expr Define a function

When defining a function, it is important to remember the underscore ( _) after each argument (x_ is actually a pattern). The underscore makes the function capable of calculating the value of the function for any value of the argument. The colon (:) before the equals sign results in the value of expr not being calculated in the definition; the value is calculated only when using the function. In everyday use of Mathematica, we rarely need to define functions for expressions to be, for example, differentiated, integrated, or plotted. Mostly we can use the expressions as such or we can give a name to the expression and then use that name. For example, consider integration. First, we directly enter the expression to be integrated into the command: [email protected] ê Ha + xL, xD

x -a [email protected] + xD

Then we give a name for the expression and use that name: f = x ê Ha + xL;

[email protected], xD

x -a [email protected] + xD

We can also define a function and then use it: [email protected]_D := x ê Ha + xL

[email protected]@xD, xD

x -a [email protected] + xD

However, this is unnecessarily complicated. The first two methods are the most useful. Giving a name is especially handy if we do several calculations with the same expression. Function definitions are mostly used to form more complicated functions and programs. For example, here is a function for calculating the characteristic polynomial of a matrix: [email protected]_, x_D := [email protected] - x [email protected]@mDDD

The following is an example of using the function: [email protected], 5<, 83, 1<<, xD

-13 -3 x +x2

‡ Programs f[x_] := Module[{local variables}, body] Define a function as a module

More complicated programs are often written as modules. In a module, we can define local variables that are only used within the module and that have no values outside the module. As an example, we develop a program to simulate random walk, in which the object starts at zero and moves one step up or down, each with a probability of 0.5. In the following way, we can generate the steps: [email protected]; [email protected], 1<, 20D 81, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1<

40

Mathematica Navigator 2%-1

81, -1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1<

Here, we first generated 20 random 0’s and 1’s. Each element of this list is multiplied with 2, and 1 is then subtracted from each element. The result is a list of random 1’s and -1’s. The random walk is the cumulative sum of the steps. Cumulative sums can easily be calculated with Accumulate: 81, 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 2, 1, 0, 1, 0, 1, 2< [email protected]%D

Thus, a program for a random walk with n steps could be written as follows: [email protected]_D := [email protected], walk<, steps = 2 [email protected], 1<, nD - 1; walk = [email protected]; [email protected], ImageSize Ø 200DD

The variables steps and walk in the program are local and thus they have no value outside the module. We simulate 200 steps of the random walk: [email protected]; [email protected] 15

10

5

50

100

150

200

Commands in a program can often be nested, as in the following: [email protected]_D := [email protected]@2 [email protected], 1<, nD - 1DD

In this way, the code of the program becomes shorter, but the readability of the code may also become weaker.

2.3 Mathematics 2.3.1 Differential and Integral Calculus ‡ Differential Calculus D[f, x] Derivative of f with respect to x D[f, x, x] Second-order derivative of f with respect to x D[f, x, y] Mixed second-order derivative of f with respect to x and y Series[f, {x, a, n}] nth-order Taylor series of f with respect to x at a Limit[f, x Ø a] Limit of f as x approaches a

Here are some examples: a = x [email protected];

Chapter 2 • Sightseeing

41

[email protected], xD, [email protected], yD, [email protected], x, xD, [email protected], x, yD, [email protected], y, yD< [email protected], x [email protected], 0, [email protected], -x [email protected]< [email protected]@[email protected], 8x, 0, 4
x3ë2

+

6

x5ë2

x7ë2

-

120

+ [email protected]ë2

5040

[email protected] + c ê xL ^ x, x Ø ¶D

‰c

(Recall that ¶ can be written as Infinity or as ÂinfÂ.) ‡ Integral Calculus Integrate[f, x] Indefinite integral of f with respect to x Integrate[f, {x, a, b}] Definite integral of f when x varies from a to b NIntegrate[f, {x, a, b}] Calculate the definite integral by numerical methods Sum[f, {i, a, b}] Sum of the values of f when i varies from a to b

Prepare to see special functions when you integrate functions that are not easy: a = [email protected]@[email protected], xD

SinIntegralA‰x E

This is one of the many special functions in Mathematica. Do not worry! You can do the same with the special functions as you do with the more usual functions. For example, you can check the result by differentiation: SinA‰x E

[email protected], xD

You can ask for a value: a ê. x Ø 1.

1.82104

You can ask for a plot:

[email protected], 8x, 0, 3
1.0

1.5

2.0

2.5

3.0

a =.

Sometimes even Mathematica does not know an integral: [email protected]@[email protected], 8x, 0, 1
[email protected]@xDD „ x 1

0

Mathematica just writes the command as such. You can then resort to numerical integration (Gaussian quadrature): [email protected]@[email protected], 8x, 0, 1
Sums are calculated like integrals: [email protected] ê 2 ^ n, 8n, 1, 10
1023 1024

0.430606

42

Mathematica Navigator [email protected] ê n ^ 2, 8n, 1, ¶
p2 r H-1 + rm L 6

[email protected] ^ n, 8n, 1, m
-1 + r

2.3.2 Matrices {a, b, c} A vector {{a, b, c, d}, {e, f, g, h}} A matrix with two rows

A 1D list is also a vector; a 2D list is a matrix. Vectors and matrices can have as many elements as you want. Mathematica does not distinguish column and row vectors but, nevertheless, it does calculations with matrices and vectors so that the results are, almost always, what you intended. We define a vector: a = 82, 5<;

A useful fact to know is that Mathematica automatically does all operations with vectors element by element: 8a ^ 2, [email protected], a ê 83, 6<< :84, 25<, :

2 ,

2 5 5 >, : , >> 3 6

Here is a matrix:

[email protected] = 882, 1<, 83, 2<
Note that MatrixForm is used only in displaying matrices. You cannot do any calculations with such a form. If you would write m = {{2, 1}, {3, 2}} // MatrixForm, then the value of m would be the matrix form of the given matrix, and with such an m we cannot calculate. However, you could write (m = {{2, 1}, {3, 2}}) // MatrixForm. a m The product of a scalar a and a vector or matrix m m + n The sum of two vectors or matrices m and n m^2 The squares of the elements of a vector or matrix m m.n The product of two vectors or matrices m and n Transpose[m] or m¨ The transpose of a matrix m (write ¨ as ÂtrÂ) Det[m] The determinant of a square matrix m

Inverse[m] The inverse of a square matrix m Eigenvalues[m] The eigenvalues of a square matrix m

Note that the point (.) has to be used when calculating products of vectors and matrices; the space and the asterisk do not work properly. You cannot use powers, either. Thus, to calculate the second matrix power of a matrix m, you have to write m.m; you cannot write m^2 (this only calculates the squares of each element). Also, to calculate the inverse of a matrix m, you have to write Inverse[m]; you cannot write m^-1. The transpose command ¨ can be written as ÂtrÂ. In the following example, a is interpreted to be a row vector: a.m

819, 12<

Here, a is a column vector:

Chapter 2 • Sightseeing

43

89, 16<

m.a

We calculate the square, transpose, determinant, inverse, and eigenvalues of m: m.m m¨

887, 4<, 812, 7<<

882, 3<, 81, 2<<

[email protected]

1

882, -1<, 8-3, 2<<

[email protected]

:2 +

[email protected]

3 , 2-

3 >

[email protected], mD

2.3.3 Equations ‡ Polynomial Equations: Exact Solutions expr1 ã expr2 An equation (ã can be written as ==) Solve[eqn, x] Solve a (polynomial) equation with respect to x Solve[{eqn1, eqn2}, {x, y}] Solve two (polynomial) equations with respect to x and y

Equations are formed with two equal signs (==), but Mathematica replaces them with the special symbol ã. Forgetting the second = is a common error; remember that = is used only to assign values for variables. Here is a polynomial equation familiar to you (we give the name eqn to this equation): eqn = a x ^ 2 + b x + c ã 0 c + b x + a x2 ã 0 sol = [email protected], xD ::x Ø

-b -

b2 - 4 a c

>, :x Ø

-b +

2a

b2 - 4 a c

>>

2a

The result is in the form of transformation rules. If you want only the values of x, apply the transformation rule to x (see Section 2.2.1, p. 32): x ê. sol :

-b -

b2 - 4 a c

-b +

b2 - 4 a c

, 2a

>

2a

We can also check that the solution is correct by inserting the solution into the equation: eqn ê. sol êê Simplify 8True, True<

Then we solve two linear equations (larger systems are solved similarly). Enclose a system of equations and the variables within curly braces ({ }): [email protected] x + 5 y ã 4, x - 3 y ã 3<, 8x, y
::x Ø

27 11

,yØ-

2 11

>>

44

Mathematica Navigator

‡ Polynomial Equations: Numerical Solutions NSolve[eqn, x] Solve a (polynomial) equation with numerical methods

Polynomial equations of a degree higher than four can rarely be solved: eqn2 = x ^ 5 - x ^ 3 + x ^ 2 - 2 ã 0; [email protected], xD

99x Ø RootA-2 + Ò12 - Ò13 + Ò15 &, 1E=,

9x Ø RootA-2 + Ò12 - Ò13 + Ò15 &, 2E=, 9x Ø RootA-2 + Ò12 - Ò13 + Ò15 &, 3E=,

9x Ø RootA-2 + Ò12 - Ò13 + Ò15 &, 4E=, 9x Ø RootA-2 + Ò12 - Ò13 + Ò15 &, 5E==

We did not obtain the solution in an explicit form (Mathematica only gives a symbolic list representing the five roots). We can now ask a decimal value: % êê N

88x Ø 1.17525<, 8x Ø -1.09595 - 0.361002 Â<, 8x Ø -1.09595 + 0.361002 Â<, 8x Ø 0.508323 - 1.00984 Â<, 8x Ø 0.508323 + 1.00984 Â<<

We can also directly resort to numerical methods: 88x Ø -1.09595 - 0.361002 Â<, 8x Ø -1.09595 + 0.361002 Â<, 8x Ø 0.508323 - 1.00984 Â<, 8x Ø 0.508323 + 1.00984 Â<, 8x Ø 1.17525<< [email protected], xD

‡ Transcendental Equations Solve can solve some transcendental equations: [email protected]@a xD ã b, xD Solve::ifun : Inverse functions are being used by Solve, so some solutions may not be found; use Reduce for complete solution information. à [email protected] >> ::x Ø a

However, FindRoot is the general-purpose command for such equations. It calculates a zero iteratively by Newton’s method and other methods. FindRoot[eqn, {x, x0}] Solve an equation with numerical methods, starting from x0

To find a zero for the following function, we first plot it: f = [email protected] - 0.5 x; [email protected], 8x, 0, 3
-0.5

0.5

1.0

1.5

2.0

2.5

3.0

-1.0 -1.5

The zero seems to be near one, and so we start from this point: x0 = [email protected] ã 0, 8x, 1
8x Ø 0.852606<

Chapter 2 • Sightseeing

45

The value of the function at this point is zero, with a high degree of accuracy: f ê. x0

-5.55112 μ 10-17

2.3.4 Optimization ‡ Global Optimization: Exact Solutions Minimize[f, vars] Give the global minimum of f with respect to variables vars Minimize[{f, cons}, vars] Minimize subject to constraints cons

We also have Maximize that is used in the same way. Consider the following function: f = x ^ 4 - 2 x ^ 3 - 2 x ^ 2 - 1; [email protected], 8x, -2, 3
-1

-5

1

2

3

The function has a finite global minimum point but not a finite global maximum point: [email protected], xD

8-9, 8x Ø 2<<

[email protected], xD Maximize::natt : The maximum is not attained at any point satisfying the given constraints. à 8¶, 8x Ø -¶<<

The function also has a local minimum point and a local maximum point. They can be found by constraining x suitably: [email protected], x < 0<, xD

:-

19

16 [email protected], -1 ê 2 < x < 2<, xD

, :x Ø -

>> 2 8-1, 8x Ø 0<< 1

Next, we solve a linear programming problem:

[email protected] + y, y ¥ x, y ¥ -2 x + 1<, 8x, y
2 1 1 : , :x Ø , y Ø >> 3 3 3

‡ Global Optimization: Numerical Solutions NMinimize[f, vars] Give the global minimum of f with respect to variables vars NMinimize[{f, cons}, vars] Minimize subject to constraints cons

We also have NMaximize that is used in the same way. For the following function, we do not get an explicit minimum point with Minimize: f = x ^ 6 + x ^ 4 + x + 1;

46

Mathematica Navigator [email protected], xD

:1 + RootA1 + 4 Ò13 + 6 Ò15 &, 1E + RootA1 + 4 Ò13 + 6 Ò15 &, 1E + RootA1 + 4 Ò13 + 6 Ò15 &, 1E , 4

6

9x Ø RootA1 + 4 Ò13 + 6 Ò15 &, 1E=>

We can ask for the solution in a decimal form: % êê N

80.569105, 8x Ø -0.555036<<

We can also directly resort to numerical methods: [email protected], xD

80.569105, 8x Ø -0.555036<<

‡ Local Optimization FindMinimum[f, {x, x0}] Find a local minimum of f starting from x0 FindMinimum[f, {{x, x0}, {y, y0}, … }] Start from x0, y0, …

We also have FindMaximum that is used in the same way. These commands use iterative methods to find local minimum and maximum points. Consider the following function: f = [email protected] + [email protected] + xD;

[email protected], 8x, 0, 2
1.0

1.5

2.0

The maximum seems to be near 0.5 and so we start from this point: x0 = [email protected], 8x, 0.5
81.29686, 8x Ø 0.650752<<

Thus, the local maximum is at the point 0.650752, and the maximum value is 1.29686. The derivative of the function at the given point is indeed zero with a high degree of accuracy: [email protected], xD ê. [email protected]@2DD

6.83054 μ 10-12

2.3.5 Interpolation and Approximation ‡ Interpolation Interpolation[data] Find a piecewise third-degree interpolating polynomial for data

Let us first generate some data:

points = [email protected], [email protected]@xDD<, 8x, 0., 2., 0.2
880., 0.540302<, 80.2, 0.342328<, 80.4, 0.0788896<, 80.6, -0.248685<, 80.8, -0.608957<, 81., -0.911734<, 81.2, -0.984107<, 81.4, -0.610894<, 81.6, 0.238328<, 81.8, 0.972854<, 82., 0.448356<<

Chapter 2 • Sightseeing

47

p1 = [email protected] 1.0 0.5 0.5

1.0

1.5

2.0

-0.5 -1.0

We now calculate a piecewise third-degree interpolating polynomial through the points: int = [email protected] [email protected], 2.<<, <>D

Mathematica calls the result an interpolating function. We do not see the actual function but, rather, only the interval where it is defined. However, we can calculate values of the interpolating function: [email protected]

-0.208865

We can plot it:

p2 = [email protected]@xD, 8x, 0, 2
1.0

1.5

2.0

-0.5 -1.0

The interpolating function goes exactly through all the given points and is of degree 3 between each pair of points: [email protected], p2D 1.0 0.5 0.5

1.0

1.5

2.0

-0.5 -1.0

The result is a good representation of the data. In Section 2.3.6, when we solve differential equations numerically, we encounter these functions: The numerical solution is expressed as an interpolating function. ‡ Approximation Fit[data, basis, var] Fit data by a linear combination of functions of var in basis Fit calculates a least-squares function to smoothly represent data containing errors. Consider the following data: data = 880, 0.185<, 81, 0.935<, 82, 0.649<, 83, 1.231<, 84, 2.279<, 85, 3.913<, 86, 4.670<, 87, 5.620<, 88, 6.767<, 89, 9.044<, 810, 11.045<<;

48

Mathematica Navigator p1 = [email protected] 10 8 6 4 2 0

2

4

6

8

10

The points seem to follow roughly a quadratic pattern, and so we try a quadratic fit: lsq = [email protected], 81, x, x ^ 2<, xD

0.293972 + 0.146282 x + 0.0910618 x2 p2 = [email protected], 8x, 0, 10
4

6

8

10

To see how close the fit is to the data, we can show both: [email protected], p2D 10 8 6 4 2 2

4

6

8

10

The fit seems to be good.

2.3.6 Differential Equations ‡ Symbolic Solutions sol = y[t] /. DSolve[eqn, y[t], t] Give the general solution of a differential equation sol = y[t] /. DSolve[{eqn, y[a] ã a}, y[t], t] Solve a first-order initial value problem sol = y[t] /. DSolve[{eqn, y[a] ã a, y'[a] ã b}, y[t], t] Solve a second-order initial value

problem Plot[sol, {t, a, b}] Plot the solution

A differential equation is like a usual equation containing ==, but now the equation contains an unknown function such as y[t] and its derivatives such as y'[t] and y''[t]. Note that initial conditions must also be written as equations (containing ==). DSolve can solve a large number of differential equations. We first ask for a general solution to the following linear equation with constant coefficients: eqn1 = y '@tD ã a [email protected] + b

y£ @tD ã b + a [email protected]

Chapter 2 • Sightseeing

49 ::[email protected] Ø -

[email protected], [email protected], tD

b

+ ‰a t [email protected]>>

a

The solution is in the familiar form of a transformation rule. The C[1] is an undetermined constant. Often, it is useful to directly ask the value of y[t]: [email protected] ê. [email protected], [email protected], tD

:-

b

+ ‰a t [email protected]>

a

Then we solve a first-order initial value problem: eqn2 = y '@tD + 2 t [email protected] - t ã 0;

sol2 = [email protected] ê. [email protected], [email protected] ã 0<, [email protected], tD :

1

‰-t J-1 + ‰t N> 2

2

2

We plot the solution:

[email protected], 8t, 0, 3
1.0

1.5

2.0

2.5

3.0

Next, we solve a second-order initial value problem and plot the solution: eqn3 = y ''@tD + [email protected] ã -t;

sol3 = [email protected] ê. [email protected], [email protected] ã 0, y '@0D ã 1<, [email protected], tD 8-t + 2 [email protected]<

[email protected], 8t, 0, 8
-1 -2 -3 -4 -5 -6 -7

2

4

6

8

‡ Numerical Solutions

If Mathematica is not able to solve a differential equation symbolically with DSolve, then we can resort to numerical methods with NDSolve. We can simply replace t with {t, a, b} defining the interval Ha, bL where the solution is calculated. sol = y[t] /. NDSolve[{eqn, y[a] ã a}, y[t], {t, a, b}] Solve a first-order equation numeri-

cally sol = y[t] /. NDSolve[{eqn, y[a] ã a, y'[a] ã b}, y[t], {t, a, b}] Solve a second-order

equation numerically Plot[sol, {t, a, b}] Plot the solution

Mathematica cannot solve the following nonlinear initial value problem:

50

Mathematica Navigator eqn4 = y ''@tD ã [email protected] ^ 2 + t; [email protected], [email protected] ã 0, y '@0D ã 1<, [email protected], tD

DSolveA9y££ @tD ã t - [email protected] , [email protected] ã 0, y£ @0D ã 1=, [email protected], tE

However, we can use numerical methods and obtain an approximate solution:

sol4 = [email protected] ê. [email protected], [email protected] ã 0, y '@0D ã 1<, [email protected], 8t, 0, 7[email protected]<

The solution is expressed as an interpolating function~that is, as a piecewise third-degree interpolating polynomial (we considered these in Section 2.3.5, p. 46). We plot the solution: [email protected], 8t, 0, 7
2

3

4

5

6

7

3 Notebooks Introduction 51 3.1 Working with Notebooks 52 3.1.1 Saving, Opening, and Printing 52 3.1.2 Cell Styles and Style Sheets 54 3.1.3 Palettes, Hyperlinks, and Slide Shows 56 CreatePalette, PasteButton, Hyperlink 3.2 Editing Notebooks 59 3.2.1 Methods of Editing 59 3.2.2 Modifying Styles 63 3.2.3 Useful Options 65 FontFamily, FontSize, LineSpacing, CellMargins, CellFrame, etc. 3.3 Inputs and Outputs 70 3.3.1 Forms of Input and Output 70 StandardForm, TraditionalForm, Style, Text, Panel, Pane, etc. 3.3.2 Writing Special Characters 74 3.3.3 Writing 2D Expressions 76 3.4 Writing Mathematical Documents 78 3.4.1 Introduction 78 3.4.2 Display Formulas 80 3.4.3 Inline Formulas 86 3.4.4 Automatic Numbering 89

Introduction During his stay in Berlin, Euler developed the habit of writing memoir after memoir, placing each when finished on top of a pile of manuscripts. Whenever material was needed to fill the journal of the Academy, the printers would help themselves to a few papers from the top of the pile. This meant that papers at the bottom remained there a long time and earlier papers often contained developments and improvements on later papers. Note that you may skip this chapter if you, right now, do not need to do the following: • get more information about notebooks (saving, opening, printing, styles, style sheets, palettes, hyperlinks, slide shows); • edit the outlook of notebooks; • write special characters and 2D formulas with the keyboard; or • write a mathematical document with display and inline formulas. Regardless of your level of comfort with Mathematica, it may be helpful for you to read Sections 3.1.1, 3.1.2, and 3.3.1.

52

Mathematica Navigator

This chapter emphasizes Mathematica as a writing tool. Indeed, you can use Mathematica to write all kinds of mathematical and other documents. Mathematica is a strong alternative to traditional writing tools because it has the remarkable advantages that the whole document can be done with the same high-quality application (e.g., graphics, tables, or formulas need not be prepared with other applications) and that Mathematica’s computing power gives you excellent possibilities to do all kinds of calculations needed for the preparation of your document. Adding notebook material into the Help Browser and other advanced matters about notebooks are explained in a separate document, Using Author Tools.nb, that can be found on the CD-ROM included with this book. Note also the GUIKit`, Notation`, and XML` packages.

3.1 Working with Notebooks 3.1.1 Saving, Opening, and Printing ‡ Saving

Mathematica documents are called notebooks. To save a notebook for the first time, choose Save As… from the File menu; later, choose Save to save the modified notebook. It is customary to give the notebook a name ending with .nb. The handling of file names depends somewhat on the system used. For example, in Windows, the name of a notebook will automatically end with .nb, and without this extension the system does not automatically know that the file should be opened with Mathematica. On the other hand, in MacOS X, Mathematica does not suggest a name ending with .nb; indeed, the name can be without that extension. You can arrange for the notebook to be automatically saved after each command (you must, however, do the first saving). Choose Option Inspector… from the Format menu and then choose Scope to be Selected Notebook and View to be by category. Then go to Notebook Options @ File Options and click the box for NotebookAutoSave. The notebook can also be saved in certain special formats such as LaTeX, HTML, or PDF by choosing Save As Special… from the File menu. ‡ Opening

A saved notebook can be opened by double-clicking the document or by choosing Open… from the File menu. Recently used notebooks are listed in the File @ Open Recent menu. When you open a notebook, you may observe that it no longer has the In- and Out-labels such as In[1] and Out[1]. After opening a notebook, you can continue working with it by adding new calculations, deleting old calculations, and doing other kinds of editing and modifying (this topic was considered in Section 1.5, p. 22). One important thing to know is that when you open an old notebook, you cannot directly use any of its results in the new session. For example, suppose that in the old notebook you have defined a = 5. When you open the notebook, the variable a has no value. If you want a to have the value 5 in the new session, you have to execute the command a = 5 anew (place the cursor anywhere in the relevant cell and execute). Similarly, all the results you want to use in the new session have to be recalculated. In other words, you can use only the results that have been calculated in the current session. A straightforward way to continue working with an old notebook is to re-execute all its commands by choosing Evaluation @ Evaluate Notebook. However, some commands may require substantial time for execution. A better method in such a situation may be to use the old outputs directly.

Chapter 3 • Notebooks

53

For example, if you have calculated an integral, take a copy of the output cell, place the cursor at the beginning of the output, write int =, and execute. Now you have the value of the integral in int without having to recalculate the integral. You can also save results to files and then load them in later sessions (see Section 4.3.1, p. 109). ‡ Spell Checking and Hyphenating

One of the last steps in preparing a document is the checking of the spelling. Choose Edit @ Check Spelling…. Mathematica comes with English spell checking, but you can buy spell checking for many other languages; contact Wolfram Research. A Spelling Language menu command then appears in either the Edit or the Format menu so that you may choose the language used. To find some options that control the spell checker, open the Option Inspector by choosing Format @ Option Inspector…, choose Scope to be Selected Notebook, and go into Formatting Options @ Text Content Options @ SpellingOptions. Note that, if you want it to, Mathematica will automatically hyphenate words according to the rules of English. To turn hyphenation on or off, open Option Inspector, choose Scope to be Selected Notebook, go into Formatting Options @ Text Layout Options, and click the box for Hyphenation. The international spellchecking products also contain hyphenation rules for other languages. ‡ Adjusting Printing Settings

Before printing the notebook, we can check, from File @ Printing Settings, the page setup, the margins, and the headers and footers. Headers and footers can be adjusted in the following window:

Here, we can adjust the starting page number; whether the notebook has separate left and right pages; and what to include in the left, center, and right of the headers and footers. For example, the top right header is, by default, as follows: Cell[TextData[{ Cell[TextData[{ValueBox[“FileName“]}], “Header“], Cell[““, “Header“, CellFrame -> {{0, 0.5}, {0, 0}}, CellFrameMargins -> 4], ““, Cell[TextData[{CounterBox[“Page“]}], “PageNumber“]}], CellMargins -> {{Inherited, 0}, {Inherited, Inherited}}]

54

Mathematica Navigator

This means that at the right we have the name of the file, a vertical line, and the page number. The code can be changed. For example, at the left of the right page header we can have the following code: Cell[TextData[“Chapter 3 • Notebooks“], “Header“] At the right of the right page header we can have the following code: Cell[TextData[CounterBox[“Page“]], “PageNumber“] If you want page numbers such as i, ii, iii, iv, etc., define them as follows: CounterBox[“Page“, CounterFunction -> RomanNumeral] The styles “Header” and “PageNumber” can be adjusted by the style sheet (see Section 3.2.2, p. 63) and the margin above the header by an option (see Section 3.2.3, p. 69). ‡ Adjusting Page Breaks

Before printing, it may also be useful to see the page breaks. Choose File @ Printing Settings @ Show Page Breaks. The appearance of the notebook on the screen changes to reflect the printed output. A page break between two cells is shown by a gray, thick line, and a page break within a cell is shown by a short horizontal line at the right of the window. The current page number can be seen in the bottom left corner of the window. In some special cases, you may want to manually adjust the automatically set page breaks. Suppose you want a page break between two cells. Put the cursor between the cells (a horizontal line appears) and choose Insert @ Page Break. Now there is a forced page break between the cells. Page break options are considered in Section 3.2.3, p. 69. ‡ Printing

To print your notebook, choose File @ Print…. You can print the whole notebook or a selected range of pages. You can also print selected cells by dragging over their cell brackets (or clicking the cell bracket of the first cell and then shift-clicking the cell bracket of the last cell) to select them and then choosing File @ Print Selection…. If you have problems with fonts when printing graphics, you may find useful information in Section 7.2.4, p. 193.

3.1.2 Cell Styles and Style Sheets ‡ Mathematica as an Advanced Writing Tool

An important point to understand is that Mathematica is an advanced environment for technical writing. Indeed, with Mathematica we can write a complete document with title, headings, texts, formulas, tables, graphics, inputs, and outputs. For example, each chapter of this book is a Mathematica notebook. When using Mathematica as a writing environment, two things are important: cell styles and style sheets. These are considered next. Mathematica as a writing tool is considered in Section 3.4. ‡ Cell Styles

In Mathematica, each cell has a style. The names of the styles can be seen by choosing Format @ Style (the styles can also be seen from a toolbar; choose Window @ Show Toolbar). For example, when we write a new command, the style is automatically Input, and the style of the result is Output. We can add text into the notebook with the Text style. Titles and headings of sections can be written with styles such as Title, Section, and Subsection.

Chapter 3 • Notebooks

55

The default style of a new cell is Input. However, we can change the style of a cell by highlighting its bracket and then choosing an appropriate style from Format @ Style. Or we can, before we write anything, choose the style of the next cell and then type the text. Within a cell of a certain type, we can apply other styles for smaller parts. If we want to change the appearance of all cells of a certain type in our notebook, we can just change the style of that cell; see Section 3.2.2, p. 63. One tip is that if you intend to write a new cell with the same style as the current cell (e.g., Text), choose Insert @ Cell with Same Style or press ‡÷Û in Windows or ı÷Á in Macintosh. ‡ Style Sheets

The cell styles have default settings (font, face, size, color, etc.), but we can adjust these if we are not satisfied with them. One way to adjust the styles is to choose an appropriate style sheet. A style sheet is a special notebook that defines styles for a normal notebook. The style sheets can be seen by choosing Format @ Stylesheet. The default style sheet is Default, but there are several others, such as JournalArticle, Textbook, StandardReport, and Correspondence. In preparing a notebook, try various style sheets and choose the one you prefer. Note that different style sheets define different sets of cell styles. For example, for the Memo style sheet, we have in Format @ Style only the styles Section, Text, and Input. Note also that for a given style sheet, Format @ Style does not necessarily list all available styles. For example, for the Default style sheet, the following styles are not listed but are available: Subsubsubsection, Subsubsubsubsection, SmallText, Subsubitem, and various styles for headers, footers, and page numbers. These styles can be used by choosing Format @ Style @ Other…, typing the name of the style in a separate dialog, and clicking OK. With more advanced style sheets, even more styles are not shown in the list of styles. For example, for the Textbook style sheet, a minority of available styles are listed. As an example, for equations, the style menu for this style sheet only lists the Equation and EquationNumbered styles, but we also have the following styles related with equations: EquationGroup, EquationGroupAligned, EquationGroupNumbered, EquationGroupAlignedNumbered, EquationNumber, EquationGrid, SplitEquation, Piecewise, and Matrix. The styles BookChapterNumber and BookChapterTitle (important with numbered equations) are also not listed. After you have chosen an appropriate style sheet, it may be that you would still like to change the styles of some cells. This can easily be done, as is shown in Section 3.2.2, p. 63. We can even create new style sheets. ‡ Screen Environments

In addition to style sheets, we have screen environments in Format @ Screen Environment. These allow you to modify the appearance of your notebook according to how you plan use it. When writing the notebook, you can use the Working environment (with large fonts); for presentations, the Presentation environment (with still larger fonts); for slide shows, the SlideShow environment (with slide show controllers); for small screens, the Condensed environment (with small fonts and a condensed style); and before printing, the Printout environment (to see how the notebook will look when printed). A simple way to change the size of the text on the screen is to choose an appropriate magnification percentage from the bottom of the notebook window or from Window @ Magnification.

56

Mathematica Navigator

3.1.3 Palettes, Hyperlinks, and Slide Shows ‡ Palettes

Palettes, which are available from the Palettes menu, help when you are writing inputs; see Section 1.4.1, p. 15. In addition to the built-in palettes, you may find other things you want to do with a palette. To create your own palette that pastes something when a button is pressed, use the following commands: CreatePalette[buttons, WindowTitle Ø "title"] (Ÿ6) Create a palette with the given buttons

and given title PasteButton[label, expr] (Ÿ6) Create a button that pastes expr when the button is pressed; put label on the button Button[label, action] (Ÿ6) Create a button that does action when the button is pressed; put label on the button

As an example, we create a palette containing various plotting commands for data: [email protected]@8 [email protected]"Points", [email protected]ÉDD, [email protected]"Points and vertical lines", [email protected]É, Filling Ø AxisDD, [email protected]"Joining lines", [email protected]ÉDD, [email protected]"Joining lines and fill", [email protected]É, Filling Ø AxisDD, [email protected]"Joining lines and points", [email protected]É, Mesh Ø AllDD, [email protected]"Joining lines, points, and fill", [email protected]É, Mesh Ø All, Filling Ø AxisDD
Plot Data as F

Here, we wrote the symbols É by writing \[SelectionPlaceholder] or ÂsplÂ; the symbol can also be found from the SpecialCharacters palette. With Quiet, we asked not to show some noninteresting messages. After executing the command, we can find the palette at the top right corner of the screen. The palette looks like the following:

To use the palette, click, for example, ListPlot[Ç] and write, in place of the placeholder, a list of points to be plotted. Then execute the command. Or, write first the data to be plotted, select it, click a button in the palette, and execute. To save the palette so that it appears in the Palettes menu, do as follows. Click the close button of the palette. You are asked to save the palette; save it to a place you prefer. Choose Palettes @ Install Palette…, select the file you saved, give the palette a suitable name, and click Finish. The palette now appears in the Palettes menu.

Chapter 3 • Notebooks

57

‡ Hyperlinks

Hyperlinks are special buttons that consist of underlined words in blue type. When a hyperlink is clicked, Mathematica jumps to a cell of the current notebook, to a cell in another notebook, to another notebook, or to a URL. As an example, suppose that we want to create a hyperlink from HERE to the cell above containing the subsubsection heading Hyperlinks. Do the following: •Select the destination cell (the cell bracket containing Hyperlinks in our example). •Choose Cell @ Cell Tags @ Add/Remove Cell Tags…. A dialog box appears (see the figure on the left below). At the bottom of the dialog, write a word or phrase (e.g., “Hyperlinks”) as the cell tag. It identifies the destination cell. Click Add; you can also close the dialog. •Select the word(s) (the word “HERE” in our example) in the notebook that will represent the hyperlink~that is, the words you want to be able to click in order to jump to the destination cell. •Choose Insert @ Hyperlink…. In the dialog box (see the figure on the right below), we can see all cell tags of the current notebook. Select the tag (“Hyperlinks” in our example) you created previously, and then click OK.

In the same way, we can create other kinds of hyperlinks. For example, to create a hyperlink to another notebook, simply select the word(s) in the notebook that will represent the hyperlink, choose Insert @ Hyperlink…, in the dialog box browse to the notebook, and click OK. To create a hyperlink to, for example, http://www.wolfram.com, write and select a word such as Wolfram, choose Insert @ Hyperlink…, in the dialog box write the address http://www.wolfram.com, and click OK. You will get a link such as Wolfram. The text of the hyperlink button can be edited by clicking the text near the button and then moving the cursor with the arrow keys into the button. Hyperlink["label", "URI"] (Ÿ6) Create a hyperlink that is displayed as label

Hyperlinks can also be created with the previous command. Here is an example: [email protected]"Wolfram", "http:êêwww.wolfram.com"D

Wolfram

58

Mathematica Navigator

Similarly, we can create hyperlinks to the Documentation Center: [email protected]"Integrate", "paclet:refêIntegrate"D Integrate [email protected]"calculus", "paclet:guideêCalculus"D calculus [email protected]"indefinite integrals", "paclet:tutorialêIndefiniteIntegrals"D indefinite integrals [email protected]"Fourier series package", "paclet:FourierSeriesêtutorialêFourierSeries"D Fourier series package ‡ Slide Shows

To create a slide show, choose File @ New @ Slide Show. A template of a slide show opens. Modify the template as you want, and then choose Format @ Screen Environment @ SlideShow. To change the appearance of the slide show, try several style sheets. In the creation of a slide show, we can also use the Slide Show palette available from Palettes @ SlideShow:

A new template for a slide show can be obtained by clicking New Template. A new slide can be added by clicking New Slide. The slide show environment can be chosen by clicking Slide Show; we can go back to normal view by clicking Normal. With Table of Contents we get the contents as a separate palette that has hyperlinks to the slides. If you want to convert a usual notebook into a slide show, click Convert Notebook. A new window, Notebook -> Slideshow, appears:

Chapter 3 • Notebooks

59

In this window, it reads “Choose the styles to use” and below it we have a list of the cell styles appearing in our notebook. This means that we have to select the cell styles according to which the notebook is divided into slides. For example, if our notebook contains several Section style cells and we want each section to become a slide, then we should choose the Section style by clicking the corresponding checkbox. Then click Convert. To see the new slide show, click Slide Show on the SlideShow palette. With the palette, we can also manually convert a usual notebook into a slide show. Put the cursor at a location where you want to begin a new slide, click the triangle before Extras…, and choose Paste… @ Navigation Bar from the palette. If you want the Previous/Next buttons at the end of a slide, put the cursor at this location and choose Paste… @ Previous/Next from the palette. Do this for each slide. Then click Slide Show. From the Extras we can also choose the style sheet, presentation size, and magnification of the slide show.

3.2 Editing Notebooks 3.2.1 Methods of Editing ‡ Steps

When creating a document with Mathematica, you want to be aware of how the document looks on screen and when printed out. The look can be adjusted in many ways. Proceed with the following steps: •Step 1: Select a style sheet. Try several style sheets from Format @ Stylesheet (Section 3.1.2, p. 55), and choose the one you like most. •Step 2: Modify styles. If some styles do not satisfy you in all respects, modify these styles. •Step 3: Adjust the notebook. If you still find some small parts of the document needing adjustment, modify these parts directly in the document. The key to modifying a notebook is the use of style sheets and styles. The notebook should be modified directly only in exceptional cases. Why? To save your work and to maintain the consistency of the look of the document. Suppose you want to change the font size of all text cells. You could manually change the style of each text cell, but if you then continue writing your document, you have to modify all new text cells as well. If you instead modify the styles, all text cells immediately change accordingly, and all new text cells also have the correct style. Thus, resist direct modification of the notebook, and modify the styles instead. The editing of styles is described in Section 3.2.2, p. 63. ‡ Methods

Whether you modify the styles or the document, you can use several methods in the modification: • Method 1: Use the Format menu. • Method 2: Use options directly. • Method 3: Use the Option Inspector. In the following section, we consider these methods in turn. In each method, we set values of some front-end options. All options can be set with the third method and most options with the second method, whereas only a small number of options (although important ones) can be set with the Format menu.

60

Mathematica Navigator

The Option Inspector is a tool that is used to view and modify various options of cells and notebooks, among other things. The options can also be adjusted directly, without the Option Inspector. When we use the Format menu, we actually also adjust options. Many options are explained in the Documentation Center under tutorial/ManipulatingNotebooksOverview. ‡ Method 1: Using the Format Menu

The editing tool used most often may be the Format menu. With it we can set various font options: Font, Face, Size, Text Color, and Background Color. We can also adjust Cell Dingbat, Magnification (magnifies a selection), Text Alignment, Text Justification, Word Wrapping, and Spelling Language. Furthermore, with Format we can choose the Style of each cell, use style sheets by Stylesheet and Edit Stylesheet, and choose a Screen Environment. To use the Format menu, first select with the mouse the part of the document you want to modify. The part is typically a cell (click its cell bracket), but it can also be a part of a cell (drag over the part), several cells (drag over their cell brackets), or a group of cells (click its bracket). Then, choose a suitable command from the Format menu. As an example, write an EmphasizedText cell: Here is some text. Increase the size of the font to 14 so that the cell becomes

Here is some text. To show that the Format menu actually uses options, we next show how to look at the internal code that Mathematica uses for cells. ‡ Method 2: Using the Options Directly

Front-end options are normally not visible; we only see the effect of the options. However, with a special menu command, we can see the internal code behind a cell: •Put the cursor somewhere in the cell, or select the bracket of the cell. •Open the code of the cell by choosing Cell @ Show Expression or pressing ˜÷‚ÎeÏ (˜÷ÌÎeÏ on a Macintosh). •Modify the code, if you so choose. •Close the code by choosing the same menu command again; the cell is then formatted according to the code. As examples, here are the codes of the two text cells we considered previously:

Cell["Here is some text.", "EmphasizedText"] Cell["Here is some text.", "EmphasizedText", FontSize->14] In both cases, the text is in an EmphasizedText style cell and the latter cell has an option for the font size. So, we have shown that the Format menu actually uses options. When the code is open, we also have the possibility to modify it. This is the second method of modification mentioned previously, “Use options directly.” We can directly write new options, delete options, and change values of options. For example, we could have opened the code of the cell of “Here is some text.”, written the option FontSize -> 14, and then closed the code. It may be that the more you use options and learn their names, the more you will like the direct modification of the code of the cells. In Section 3.2.3, p. 65, we list some useful options, many of which are not available with the Format menu.

Chapter 3 • Notebooks

61

‡ The Structure of Expressions and Notebooks

It may be interesting to look at the code of a mathematical result. For example, a = [email protected] + [email protected] ê 6D 1

+2

2

2

The code of the output cell is as follows (put the cursor in the result and press ˜÷‚ÎeÏ):

Cell[BoxData[ RowBox[{ FractionBox["1", "2"], "+", RowBox[{"2", " ", SqrtBox["2"]}]}]], "Output", CellChangeTimes->{3.3931306115955353`*^9}] We see that the formula is built up from various box constructs. A whole notebook consists of a list of cells, together with possible options. The general form of a notebook is thus Notebook[{cell1, cell2, …}, options]. In this way, Mathematica represents cells and notebooks as text expressions containing only 7-bit ASCII characters. From this, it follows that notebooks work independently of the platform they are opened with and thus can be used unchanged with any computer system. We shall not go into the details of cell and notebook expressions here. We only study the use of the front-end options. ‡ Method 3: Using the Option Inspector

The Option Inspector is a special window where we can view and modify the options of the front end. The window can be opened by choosing Format @ Option Inspector…, and it looks like this (here we have opened some groups of options):

62

Mathematica Navigator

The options are grouped into six categories: Global, Notebook, Cell, Editing, Formatting, and Graphics options. In the figure above, we can see options such as PageWidth and TextAlignment together with their current values. There are several hundred options, but most of us will never need the majority of them. Clicking a triangle before a category opens the category into a list of subcategories or options. This categorical listing is the default way that the Option Inspector shows the options. To use the Option Inspector to modify a part of your document, do the following: •Select the part of your document that you want to modify with options (typically the part is a cell, but it can also be a part of a cell or several cells). •Open the Option Inspector by choosing Format @ Option Inspector… or pressing ˜÷‚ÎoÏ (˜÷ÌÎoÏ on a Macintosh). •Set the values of the options you want. The values of many options can be set by check boxes, popup menus, or dialog boxes, but if you type the value, you have to press the return key Á after typing for your setting to go into effect. •Go back to your document (you can leave the Option Inspector open, in case you need it again). An option for which we have set a nondefault value has a check mark symbol before it. Clicking the check mark changes the value of the option to the default value and removes the check mark. After experimenting with some options of a cell, we may find that we would like to return to the default option values for this cell. Select the cell bracket and choose Format @ Clear Formatting. ‡ More about the Option Inspector

At the top of the window, we can select the scope of the option settings and the way the options are listed in the Option Inspector. We can also search suitable options. The scope can be Selection, Selected Notebook, or Global Preferences (we can also choose from a list of open notebooks). Indeed, a key property of Option Inspector is that it allows us to specify the level at which we want to set the value of an option: •If the scope is Selection, the option settings only affect the part of the current notebook that is selected with the mouse (the selected part may be a cell, several cells, or a part of a cell). •If the scope is Selected Notebook, the option settings only affect the current notebook. •If the scope is Global Preferences, the option settings affect the whole Mathematica application~the current session and all future sessions, all currently open notebooks, and all notebooks opened or created in the future. When working with Option Inspector, it is important to choose the suitable level; otherwise, you can easily generate unwanted effects. Note also that some options cannot be set at all levels; options that cannot be set at the currently selected level are dimmed. The options in the Option Inspector can be listed in three ways: by category, alphabetically, or as text. A listing by category is useful if you want to find out what options are available for a certain purpose. An alphabetical listing is useful if you already know the option you want to apply. The text view only shows the nondefault options as text, such as “FontSizeØ12”; this view cannot be used to set the value of an option. At the top of the Option Inspector window is a field in which we can write a word to be searched from the names of the options. For example, write font in the field to get a list of options containing font. In the next section, we show how we can edit styles, and the section following that gives lists of useful options (approximately 50 options).

Chapter 3 • Notebooks

63

3.2.2 Modifying Styles ‡ Modifying Styles

As noted in Section 3.2.1, p. 59, notebooks should be edited mainly by modifying styles, and they should be directly edited only in exceptional cases. In this section, we show how to modify styles. The starting point in modifying the styles of a notebook is the choice of a suitable style sheet from Format @ Stylesheet. Choose a style sheet that is as close to your needs as possible. If the styles do not fully satisfy you, you may want to make some modifications to the styles. Proceed as follows: • Choose Edit Stylesheet… from the Format menu. A notebook appears with the title Private Style Definitions for …. • From Choose a Style to Modify, choose the style(s) you want to modify. The corresponding style definition cells appear in the notebook. These cells show how cells having these styles look out. • Modify the style definition cells by using the methods explained in Section 3.2.1, p. 59: Use the Format menu, use options directly, or use the Option Inspector. You can immediately see the corresponding changes in your notebook. • If a style is not mentioned in Choose a Style to Modify or if you want to define a new style, use the Enter a style name input field to give a suitable name for the style; the corresponding style definition cell appears in the document. Edit this cell as you want. A new style appears in Format @ Style. • The Private Style Definitions notebook can be left open (for later modifications) or it can be closed (without saving). Note that in the previous procedure, the name of the menu command Edit Stylesheet… gives a somewhat wrong impression: We did not edit the style sheet. Rather, we created some private style definitions for our current notebook (and only for it). The private styles are based on the chosen style sheet; we only tell how we want to change the styles. Below we show a Private Style Definitions notebook. The styles are based on the Default style sheet, or, as is said in the notebook, the base definitions of the styles are inherited from the Default style sheet. We have changed the style of Section, Subsection, and Subsubsection by adding color definitions.

64

Mathematica Navigator

The modified and new styles work immediately. Whatever you have written in your notebook and whatever you write later will follow the modified styles. If you later edit the styles of the notebook in question, the same Private Style Definitions notebook opens and you can continue modifying the styles. ‡ Creating New Style Sheets

As noted, the procedure we described previously only modifies the styles of the current notebook. If you want to use your own styles for several notebooks, you should create your own style sheet as follows: • Proceed as discussed previously: Choose Format @ Edit Stylesheet… and edit the styles and add the new styles you want. • Save the style sheet by choosing Format @ Save As…. You can save it with the name and to the place you want. • Install the new style sheet by choosing File @ Install…, select Type of Item to Install to be Stylesheet, select Source to be From File…, select the new style sheet, give the style sheet a suitable name, and click Finish. The new style sheet now appears in Format @ Stylesheet. Later, if you want to continue editing the new style sheet, open a document using that style sheet and choose Format @ Edit Stylesheet…. The appearing Private Style Definitions for … notebook contains a hyperlink to the style sheet; click it. The style sheet opens and you can edit it; the changes are automatically saved. ‡ Creating New Styles

If you find yourself occasionally manually modifying a new cell of your document, this may be an indication that you should define a new cell style to your style sheet. To create a new style, we can use the Enter a style name input field in the Private Style Definitions for … notebook as described previously. Another way is to copy a suitable style definition cell from a style sheet: • For a notebook, choose a style sheet that contains a style you want to copy. Choose Format @ Edit Stylesheet, and click the hyperlink to the style sheet. • Copy a style definition cell, paste the cell into your style sheet, select the cell bracket of the new cell, choose Cell @ Show Expression, write a new representative name into StyleData["name"], and choose Cell @ Show Expression again. • Change the style of the cell according to your needs (e.g., using the Format menu). The new style then either appears in Format @ Style or can be used by writing the name of the style into the window opened by Format @ Style @ Other…. The default is to place new styles at the end of the Style menu. With the MenuPosition option we can define a suitable place. Select the cell bracket of the new style, choose Format @ Option Inspector…, set Scope to be Selection, and set the value of the mentioned option to, for example, 10 if you want the style to be the 10th item in the Style menu. ‡ Changing the Size of Printed Text

In some style sheets, the sizes of texts are quite small when printed. If you would like to increase the sizes of texts, this can be done by editing a style sheet; for more details, see the following FAQ document: http:êêsupport.wolfram.comêmathematicaêinterfaceêprintêincreasingprintoutfont.html.

Chapter 3 • Notebooks

65

3.2.3 Useful Options ‡ Formatting Options: Fonts

Most options concerning fonts can be set with the Format menu. These options can also be found from the Option Inspector, and they can be written directly into the code of the cells. FontFamily Examples of values: "Times", "Arial", "Helvetica", "Courier" FontSize Examples of values: 12, 10, 9 FontWeight Examples of values: "Plain", "Bold" FontSlant Examples of values: "Plain", "Italic", "Oblique" FontTracking Examples of values: "Plain", "Condensed", "Extended" FontColor Examples of values: Automatic, RGBColor[1, 0, 0] FontOpacity Examples of values: Automatic, 0.5 Background Examples of values: None, RGBColor[1, 1, 0] Magnification Examples of values: 1, 0.75, 1.5 FontVariations An example: {"Underline" Ø True, "Outline" Ø True}; possible variations: "Underline", "Outline", "Shadow", "StrikeThrough", "Masked", "CompatibilityType", and "RotationAngle"; each can be set to False or True, except that "CompatibilityType" can be set to "Normal", "Superscript", or "Subscript", and "RotationAngle" to an angle

These options can be found from the Option Inspector under Formatting Options @ Font Options. Note that the value of FontColor and Background for cells cannot be a special color directive such as Red or Blue; the value has to be given with RGBColor, Hue, GrayLevel, or CMYKColor (however, colors such as Red or Blue work in graphics). For color definitions, see Section 6.2.8, p. 168. In the following example, we use several font options:

An example of font options The code of this cell is as follows:

Cell[TextData[StyleBox["\tAn example of font options", Background->RGBColor[1, 1, 0]]], "Text", CellMargins->{{Inherited, Inherited}, {1, 2}}, CellChangeTimes->{3.393143437924532*^9}, FontFamily->"Times", FontSize->14, FontWeight->"Bold", FontSlant->"Italic", FontColor->RGBColor[1, 0, 0]] ‡ Formatting Options: Text Layout

The look of a document is greatly affected by various margins and spacings; we present lists of options that can be used to adjust these. The values of many of these options are given in printer’s points. One printer point is approximately 1/72 of an inch. The values of some options are given in ems or x-heights. An em is approximately the width of an “m,” and x-height is the height of an “x.” LineSpacing Specifies the spacing between successive lines of text; value is of the form {c, n},

meaning that the height of each line is c times the height of the contents of the line plus n printer’s points (n may be negative); value can also be of the form {c, n, max}, meaning that the extra space is limited to max times the height of a single line

66

Mathematica Navigator g g ParagraphSpacing The extra space between two paragraphs (a new paragraph begins after each explicit Á character); value is of the form {c, n}, meaning that the extra space is c times the height of the font plus n printer’s points ParagraphIndent The indentation, in printer’s points, of the first line of a paragraph (a new paragraph starts at the beginning of a cell and after each explicit Á); a negative value causes all but the first line to be indented TabSpacings The number of spaces, in ems, that the cursor advances (at most) when Í is pressed in a text cell; examples of values: 4, {10, 15, 12, 7} TabFilling Determines how a Í is represented; examples of values: None, ".", "Underline", "GrayUnderline"

These options can be found from the Option Inspector under Formatting Options @ Text Layout Options. LineSpacing and CellMargins, together with fonts and their sizes, are important options that affect the overall look of the pages of your document. Usually, each paragraph is in its own cell, and then CellMargins determines the spacing between paragraphs. However, if you write several paragraphs into the same cell, then ParagraphSpacing determines the space between the paragraphs in such cells. With LineSpacing, any of c, n, or max can also be zero, and then the spacing is determined only with the height of the contents or only with the given printer’s points. A typical value of this option is {1, 3}.

With a negative ParagraphIndent, we get paragraphs like this one. Usually, we need both indented and nonindented paragraphs. A normal paragraph is indented, but the first paragraph in a section is nonindented. If the same paragraph continues after a formula, we also need a nonindented paragraph. One way to use both indented and nonindented paragraphs is to let a text cell have a zero indentation and to press Í if an indentation is needed; we can give TabSpacings a suitable value. If one value, for example, m, is given for TabSpacings, then the width of the space between two tab stops is m; that is, tab stops are at positions m, 2m, 3m, etc. However, if the value is a list such as {m, n, k}, then the widths of the spaces between tab stops are m, n, k, k, k, etc. The default is that a tab is represented as white space, but we can use any character, such as a period ".", and also the values Underline and GrayUnderline. TextAlignment Examples of values: Left, Right, Center TextJustification Examples of values: 0 (natural spacing) 0.5, 1 (full justification) PageWidth Examples of values: WindowWidth, PaperWidth, n (in printer’s points) Hyphenation Possible values: False, True (see Section 3.1.1, p. 53) HyphenationOptions Ø {"HyphenationMinLengths" Ø {m, n}} A minimum of m and n characters

can be split off the start and end of a word, respectively; default value: {3, 3} (this option is most easily set with the Option Inspector) These options can be found from the Option Inspector under Formatting Options @ Text Layout Options. ‡ Formatting Options: Formulas

The following options are useful when writing mathematical formulas (the first option is explained in Section 3.4.3, p. 88). lim, max, and min; possible values: Automatic, True (display the limits as in ⁄i=1 when the

LimitsPositioning How to display limits in constructs such as sum, product, union, intersection, n

formula is inline), False (display the limits as in ⁄ ) n

i=1

Chapter 3 • Notebooks

67

ScriptMinSize Minimum font size used in subscripts, etc.; default values: 9 (on screen), 5 (on

paper) ScriptSizeMultipliers How much smaller to render each successive level of subscripts, etc.;

default value: 0.71 These options can be found from the Option Inspector under Formatting Options @ Expression Formatting. The first is under Specific Box Options in OverscriptBoxOptions, UnderscriptBoxOptions, and UnderoverscriptBoxOptions. The last two options are under Display Options. ‡ Formatting Options: Frame Boxes

If we want a frame around a smaller part than a cell, we select that part and choose Insert @ Typesetting @ Add Frame. An example is sinHxL2 + cosHxL2 = 1 . As another example, we emphasize a display formula: lim 1 +

xض

a x

x

=‰

Such frames can be controlled with FrameBoxOptions, presented later. The values of some options we will present from now on may be given in the form {{left, right}, {bottom, top}}, meaning that numerical values are given that control the left, right, bottom, and top

parts. This value is written below in the short form {{l, r}, {b, t}}. FrameBoxOptions Ø {opts} Options controlling the frame around a box (to get a frame, use Insert @

Typesetting @ Add Frame); the following options can be given: BoxFrame Whether to draw lines around a frame box. Value may be True, False, f, or {{l, r}, {b, t}}, where each number is the thickness of the frame or a part of it in printer’s points (the value True implies the value 1). FrameMargins Margins between the contents of a grid box and the surrounding frame. Left and

right margins are given in ems, and bottom and top margins are given in x-heights. Value may be True, False, m, or {{l, r}, {b, t}} (the value True implies the value {{1, 1}, {1, 1}}). FrameStyle Style of the frame; an example of value: {RGBColor[0, 0, 1]} BaseStyle Base style of the frame; an example of value: {RGBColor[1, 0, 0]} Background Background color; an example of value: RGBColor[0, 1, 0]

These options can be found from the Option Inspector under Formatting Options @ Expression Formatting @ Specific Box Options @ FrameBoxOptions. ‡ Cell Options: General CellMargins Margins, in printer’s points, around a cell; value is of the form {{l, r}, {b, t}},

where each number is the size of a part of the margin (note that left and right margins can be set with the ruler, available from Window @ Show Ruler; its unit can be set with RulerUnits) CellDingbat Dingbat to be used to emphasize a cell; examples of values: None, "‡", "\ [FilledSmallSquare]" Background Background color of a cell; examples of values: Automatic, RGBColor[1,0,0] Magnification Magnification factor for the cell; examples of values: 1, 0.75, 1.5 ShowCellLabel Whether to show cell labels; possible values: True, False

68

Mathematica Navigator

The first four options can be found from the Option Inspector under Cell Options @ Display Options and the last option under Cell Options @ Cell Labels. CellMargins determines, in addition to the white space to the left and right of the content of the cell, the white space between cells. Usually, each paragraph of text is written into its own cell, and then the cell margins determine the spacing between paragraphs.

One application of Magnification may be as follows. When using magnification values of more than 100% from Window @ Magnification, all text remains in the window, but it may be that graphics can no longer be seen completely. Setting Magnification Ø 1 for plots keeps the size of graphics the same, irrespective of the magnification percentage used for the notebook. Normally, we have labels such as In[1]:= and Out[1]= before inputs and outputs. With the ShowCellLabel option, we can turn the labels off. This can also be done with Mathematica @ Prefer-

ences @ Evaluation @ Show In/Out Names. ‡ Cell Options: Cell Frames CellFrame Whether a frame is drawn around a cell; value may be False, True, f, or {{l, r}, {b, t}}, where each number is the absolute thickness of the frame or a part of it in printer’s points (the

value True implies the value 0.25) CellFrameMargins Margins, in printer’s points, inside a frame; value may be m or {{l, r}, {b, t}}

(typical default value is 8) CellFrameColor Color of the frame; examples of values: GrayLevel[0], RGBColor[1,0,0] CellFrameLabels Labels of the frame; value is of the form {{left text, right text}, {bottom text, top text}} (the style of frame labels can be adjusted by using the style sheet) CellFrameLabelMargins Margins, in printer’s points, between a cell frame and the labels; value

may be m or {{l, r}, {b, t}} (typical default value is 6) These options can be found from the Option Inspector under Cell Options @ Cell Frame Options. With CellFrame, we can form various frames, such as the following ones: CellFrame Ø True CellFrame Ø {{0, 0}, {0, 0.25}} CellFrame Ø {{0, 0}, {0.25, 0}} CellFrame Ø {{5, 0}, {0, 1}} CellFrame Ø True, Background Ø GrayLevel[0.85] In the following example, we have cell frame labels: top left

A text with a frame and frame labels.

right bottom

Chapter 3 • Notebooks

69

‡ Cell Options: Page Breaks

Page breaks can be seen by choosing File @ Printing Settings @ Show Page Breaks. Page breaks can be manually added with Insert @ Page Break. The following options give a more detailed control of the page breaks. PageBreakAbove Whether a page break should be made above a cell; possible values: Automatic, True, False PageBreakBelow Whether a page break should be made below a cell; possible values: Automatic, True, False PageBreakWithin Whether a page break should be allowed within a cell; possible values: Automatic, True, False GroupPageBreakWithin Whether a page break should be allowed within a group of cells; possible

values: Automatic, True, False PrintingOptions Ø {"PageHeaderMargins" Ø {left, right}} Vertical margins, in printer’s

points, above the header of the left and right facing pages, respectively (recall that the margins of the pages can be set with File @ Printing Settings @ Printing Options…) The first four options can be found from the Option Inspector under Cell Options @ Page Breaking; the last option is in Notebook Options @ Printing Options @ PrintingOptions. ‡ Notebook Options

Next, we list some options typically specified at the notebook or global level. DragAndDrop Whether to allow us to drag a selection to a new location with the mouse; possible

values: False, True EvaluationCompletionAction What to do when an evaluation is completed; examples of values: {}, {"ShowTiming"} (see Section 4.4.1, p. 112) "GraphicsPrintingFormat" Format in which PostScript graphics are to be printed; possible values: "Automatic", "RenderInFrontEnd", "DownloadPostScript", "Bitmap" (see Section 7.2.4, p. 193) ImageSize Size of an image; default value: {350, 350} (see Section 5.1.1, p. 120) InputAutoReplacements Sequences of characters that are automatically replaced with other

characters; default value for input cells: {"->" Ø "Ø", ":>" Ø "ß", "<=" Ø "§", ">=" Ø "¥", "!=" Ø "", "==" Ø "ã", ParentList} NotebookAutoSave Whether the notebook should automatically be saved after each command

execution; possible values: False, True (see Section 3.1.1, p. 52) RulerUnits Determines the units in the ruler toolbar; possible values: "Inches", "DecimalInches", "Points", "Picas", "Centimeters", "Millimeters" SpellingOptions Determines settings for spell checking (see Section 3.1.1, p. 53) ‡ Preferences

The preferences of Mathematica can be found (in a Macintosh) from Mathematica @ Preferences. There, we can globally adjust many options. For example, the following figure shows how the display of numbers can be adjusted.

70

Mathematica Navigator

3.3 Inputs and Outputs 3.3.1 Forms of Input and Output ‡ Forms of Output

Mathematica can show results in several forms. The forms are InputForm, OutputForm, StandardForm, and TraditionalForm. The default form is StandardForm. As an example, we calculate an integral and show the result with all four format types: [email protected]@xD ê Ha ^ 2 + b ^ 2 xL, xD êê InputForm

(2*Sqrt[x])/b^2 - (2*a*ArcTan[(b*Sqrt[x])/a])/b^3 [email protected]@xD ê Ha ^ 2 + b ^ 2 xL, xD êê OutputForm b Sqrt[x] 2 a ArcTan[---------] -------2 Sqrt[x] a ---------------- - ---------------------------------------2 3 b b

[email protected]@xD ê Ha ^ 2 + b ^ 2 xL, xD êê StandardForm 2

x

2 a ArcTanB -

b

x a

F

b2 b3 [email protected]@xD ê Ha ^ 2 + b ^ 2 xL, xD êê TraditionalForm 2

x b2

2 a tan-1 -

b

x a

b3

InputForm is a linear or 1D form that uses only standard characters. OutputForm is a 2D form that also uses only standard characters. Both of these forms are only rarely used. One application of the input form is to ask for all of the 16 decimals that Mathematica uses in its internal calculations:

Chapter 3 • Notebooks p êê N

71

3.14159

% êê InputForm

3.141592653589793

StandardForm is a 2D form and uses special characters such as , special spacings, and special character sizes. This is the default form of output (so writing //StandardForm above was unnecessary). TraditionalForm imitates all aspects of traditional mathematical notation. For example, variables are in italics, arguments of functions are in parentheses ( ) and not in square brackets [ ], and other traditional notations such as tan-1 (instead of ArcTan) are used. This form is mainly used in preparing mathematical documents. In addition to the commands such as InputForm, we can also use the menu command Cell @ Convert To. Note that Mathematica has many more formatting commands: 8AccountingForm, BaseForm, BlankForm, BoxForm, CForm, ColonForm, ColumnForm, DisplayForm, EdgeForm, EngineeringForm, FaceForm, FontForm, FortranForm, FullForm, HoldForm, HorizontalForm, HornerForm, InputForm, LineForm, LongForm, MathMLForm, MatrixForm, NumberForm, OutputForm, PaddedForm, ParentForm, PointForm, PolynomialForm, PrecedenceForm, PrintForm, PromptForm, RealBlockForm, RecurringDigitsForm, RuleForm, ScientificForm, SequenceForm, ShowShortBoxForm, SpaceForm, StandardForm, StringForm, StyleForm, SyntaxForm, TableForm, TeXForm, TextForm, TraditionalForm, TreeForm, ValueForm, VerticalForm< [email protected]"*Form"D

For dynamic ways to show outputs, see Chapters 12 and 13. ‡ Style and Text Style[expr, dirsOpts] (Ÿ6) Show expr with the specified directives and options Text[expr] (Ÿ6) Show expr in plain text format Style is mainly used to adjust font properties. Font directives and options are considered in Section

6.2.6, p. 163. We have such options as FontSize, FontWeight, FontSlant, FontColor, FontFamily, and Background. However, the size, weight, slant, and color can also be defined simply by giving the value of the option (i.e., the option itself need not be mentioned): [email protected]@x [email protected], xD, 12, Bold, Italic, Blue, FontFamily Ø "Helvetica", Background Ø YellowD

-x Cos @x D + Sin @x D

With Text we can easily change the usual Courier font in the outputs to the Times font: [email protected] [email protected], xD êê Text

-x [email protected] + [email protected] One of the options of Style is DefaultOptions. This option may sometimes be useful to change the style of some objects without having to put the same set of options into each object: [email protected]@8Red, [email protected]
,

,

>

72

Mathematica Navigator

‡ Framed, Panel, Labeled, and Pane Framed[expr] (Ÿ6) Put a frame around expr Panel[expr] (Ÿ6) Display expr as a panel Panel[expr, title] Give the panel the title title Panel[expr, title, pos] Put the title at position pos Labeled[expr, label] (Ÿ6) Give expr the label label Labeled[expr, label, pos] Put the label at position pos Pane[expr, w] (Ÿ6) Show expr as a pane; set the width to w printer’s points Pane[expr, {w, h}] Set the width and height to w and h printer’s points, shrinking the contents if

necessary With Framed we can use the options Background, FrameMargins, FrameStyle, and ImageMargins. [email protected] [email protected], xD êê Framed -x [email protected] + [email protected] [email protected]@x [email protected], xD, FrameMargins Ø 7D -x [email protected] + [email protected]

With a panel we get a gray background: [email protected]@x [email protected], xDD

-x [email protected] + [email protected] [email protected]@x [email protected], xD, "Integral"D

Integral -x [email protected] + [email protected] [email protected]@x [email protected], xD, "Integral", BottomD

-x [email protected] + [email protected] Integral Examples of a label:

[email protected]@x [email protected], xD, "Integral" êê TextD -x [email protected] + [email protected]

Integral

[email protected]@x [email protected], xD, "Integral" êê Text, 88Top, Right<
Integral -x [email protected] + [email protected]

A pane is useful if we would like to put the output on an area of fixed width and/or fixed height: [email protected]@nD, 8n, 1, 30
82, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113<

Chapter 3 • Notebooks

73

[email protected]@[email protected], 8n, 1, 30
82, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113<

Some commands have the Frame option and various options for labels. However, with Framed and Labeled we get somewhat different results. Here, we use Plot as an example: [email protected]@xD, 8x, 0, 2 p<, Frame Ø TrueD, [email protected]@xD, 8x, 0, 2 p
:

1.0

1.0

0.5

0.5

0.0

,

-0.5

1

2

3

4

5

>

6

-0.5

-1.0 0

1

2

3

4

5

-1.0

6

[email protected]@xD, 8x, 0, 2 p<, PlotLabel Ø [email protected], [email protected]@[email protected], 8x, 0, 2 p
1.0

1.0

:

0.5

0.5

, 1

2

3

4

5

-0.5

6

1

2

3

4

5

6

>

-0.5 -1.0

-1.0

sinHxL ‡ Forms of Input

Inputs can be written both in a 1D and in a 2D form. For example: [email protected] ê 2 Hx ^ 2 + a Pi ê xL [email protected], 8x, 0, 1


1

0

7 2

x2 +

ap

x „x

1 +7 a p

1 +7 a p

x

In the latter form, we used the BasicMathInput palette; see Section 1.4.1, p. 15, regarding the use of palettes to write 2D inputs. In Section 3.3.3, p. 76, we learn how to write 2D inputs without palettes using special key combinations. Choosing between the 1D and 2D input forms may mainly be a matter of habit. I personally use 1D inputs because they are straightforward to write with the keyboard and because I then do not need the mouse, the palettes, or special key combinations. However, 2D inputs are very clear and illustrative because they resemble traditional mathematical notation. From a 2D input, we can more easily check that the input is correct. Using palettes to form inputs may be handy at least in the early stages of learning the use of Mathematica because the user then does not need to remember the form of, for example, an integrating command. A compromise may be to write in 2D form only the parts of the input that can easily be written with the keyboard: 7 IntegrateB 2

x2 +

ap

x , 8x, 0, 1
1 +7 a p

x

Still another way is to write a 1D input and then convert it to 2D form with Cell @ Convert To @ StandardForm. In Sections 3.3.2 and 3.3.3, we learn how to write special characters and 2D inputs.

74

Mathematica Navigator

3.3.2 Writing Special Characters ‡ Introduction

Mathematica has a large set of special characters such as p, ¶, œ, and ⁄. To write these characters, we have several possibilities. As an example, we consider various ways to write ¶. 1.In an input, we can write Infinity. 2.From the keyboard, we can possibly find ¶ (on a Macintosh, press ıÎ5Ï). 3.All characters have a full name; for ¶, it is \[Infinity]. After we have typed ], the sequence of characters transforms to ¶. 4.Many characters also have an alias. For ¶, it is Âinf ( means the escape key; it appears as Ç on the screen). After pressing the second Â, the sequence of characters transforms to ¶. This is a very handy way to type special characters, although we have to remember the aliases. 5.Many characters can be found in the BasicMathInput palette; more are found in the BasicTypesetting and SpecialCharacters palettes (the latter palette can also be opened from Insert @ Special Character…). By moving the mouse over the BasicTypesetting palette, we can see the aliases of the characters at the bottom of the palette. By clicking a character in the SpecialCharacters palette, we can see both the full name and the alias of the character. In this way, we can learn the aliases and full names so that we possibly more rarely need to use the palettes. In addition, characters can be typed using TeX aliases such as Â\infty or HTML and SGML aliases. During the early stages of learning to use Mathematica, it may be handy to use the palettes. In time, it may be more useful to learn the aliases of the characters you need often. When we next study in some detail the special characters of Mathematica, we will give the aliases of the characters. Characters are also explained in the Documentation Center under tutorialêMathematicalAndOtherNotationOverview. ‡ Greek and Other Letters

char.

a b g d e  z h q J i k ø l m n x

p v r  s t u

f j c y w

alias

a b g d e ce z h q cq i k ck l m n x om p cp r cr s t u

o

f j c y o

char.

A B G D E

Z H Q

I K

L M N X O P

R

S T U ¢ F

C Y W

alias

A B G D E

Z H Q

I K

L M N X Om P

R

S T U cU F

C Y O

The second and fourth rows tell how the alias of a Greek letter is formed: For example, to write g, press ÂgÂ, or to write G, press ÂGÂ. In general, these aliases are easy to remember: The alias is formed by the corresponding usual letter (exceptions are q for q and y for y, among others). The “c” letter in some aliases comes from “curly.” If you do not remember this kind of short alias, you can use a longer alias containing the whole name of the Greek letter, for example, Âgamma or ÂGammaÂ. In addition to Greek letters, Mathematica has script letters such as , , , , , , , , , , Gothic letters such as , , , , , , , , , , and double-struck letters such as , , , , , , , , , . Their aliases are formed by enclosing, for example, sca, scA, goa, goA, dsa, or dsA with  keystrokes. In the following table, we have collected some special symbols: char. alias

p ‰ Â ¶ p ee ii inf

    dsC dsR dsQ dsZ dsN

Chapter 3 • Notebooks

75

For example, to write p, type ÂpÂ. Note that among the Greek letters, only p has a special meaning in Mathematica. , , , , and  are often used to denote the set of complex, real, rational, integer, and natural numbers, respectively. In outputs, Mathematica uses the first four symbols given in the table for Pi (= 3.141), E (= 2.718), I (= 8Pi, E, I, Infinity<

-1 ), and Infinity, respectively: 8p, ‰, Â, ¶<

‡ Mathematical Symbols

char.



°

μ

ä

ÿ

,







Ÿ

ò

alias

+-

-+

*

cross

.

sqrt

pd

del

dd

int

cint

char. alias

œ el

– !el

º ~~

> @ ~= ~==

char. alias

fl ñ => <=>

Ø ->

ö -->

char. alias

co

æ ct

 hc

tr

‹ un

Õ Œ sub sub=

¨ <-> d lf

› « ª inter es === " fa t rf

$ ex ` lc

± !ex p rc

fl and P @@

fi or T DD



P

sum prod  !=

Ÿ not

X <

 prop

 pw

± deg

† fssq

\ >

For example, to write ±, type Â+|Â. The symbol  means multiplication, ä the cross-product of two vectors,  partial differentiation, “ a gradient or a backward difference, „ the differential in an integral, « an empty set, conjugate, transpose, æ conjugate transpose,  Hermitian conjugate, d and t left and right floor, ` and p left and right ceiling,  a piecewise definition, and ° degree. Among the symbols in the table, many have special mathematical meanings in Mathematica. Such symbols include , ä, ,, , Ÿ, ⁄, ¤, , œ, ‹, ›, fl, ", $, fl, fi, ¬, , , æ, , d, t, `, p, , and °. For example, :2 μ 4, 81, 2, 3< ä 8a, b, c<,

,

4, x [email protected], ‡ [email protected] „ x, ‚ i, 4

i=1

8a, b, c< › 8a, c, d<, Ÿ HTrue Ï FalseL, H2 - 3 IL, d5.8t, 180 ± êê N> 88, 8-3 b + 2 c, 3 a - c, -2 a + b<, 2, [email protected], [email protected], 10, 8a, c<, True, 2 + 3 Â, 5, 3.14159< ‡ Characters for Fine-Tuning

\@InvisibleSpaceD \@VeryThinSpaceD \@ThinSpaceD \@MediumSpaceD \@ThickSpaceD

Âis Ââ Âââ Ââââ ÂââââÂ

\@InvisibleCommaD \@NonBreakingSpaceD \@NoBreakD \@IndentingNewLineD \@AlignmentMarkerD

 , Ânbs Ânb Ânl ÂamÂ

For each character, the table shows the full name and the alias. Mathematica has some special characters that are useful for fine-tuning text and expressions. One of them is an invisible comma. An example is xij , where we used an invisible comma between i and j. If we write i and j one after another, the indices are not italicized: xij . If we write a space between i and j, the indices may be too far from each other: xi j . Another special character is an invisible space. An example is xy, where we used an invisible space between x and y. Such an xy may be used as the product of x and y if we think that a space between x

76

Mathematica Navigator

and y is not aesthetically what we want: x y. We also have an implicit plus to display mixed fractions 3

such as 5 4 ; write the implicit plus as Â+Â. We also have spaces of various widths; note that â means the space key. Not shown in the previous box are the corresponding negative spaces from \[NegativeVeryThinSpace] to \[NegativeThickSpace], which allow us to move characters nearer to each other. We also have a space that does not allow a break (i.e., the words on both sides of the nonbreaking space will always be on the same text line) and a character that does not allow a break. Note that the special spaces are of fixed width and thus do not stretch like a normal space. An indenting character inserts a line break while always maintaining the correct indenting level [a usual new line character (¿) sets the indenting level at the time the new line is started]. With an alignment marker, we can tell how to align rows, for example, in a mathematical formula containing several rows (see Example 5 in Section 3.4.2, p. 83). ‡ Keys on a Keyboard

char.

¯

alias

spc

â

Í

¿

Á

space tab ret âret

Û ˜ ‚ ‡ ent

sh

ctrl

alt

Ç

Â

·

Ì ı

esc âesc cmd cl

opt



Î Ï

÷

âdel @ D kb

These characters are useful in describing the use of the keyboard.

3.3.3 Writing 2D Expressions ‡ 2D Constructions

Recall that we can write inputs in a 2D form by using palettes. Now we learn how to write such inputs with the keyboard. These techniques are also useful when writing formulas in a mathematical document (see Section 3.4). 2D expressions are written with the control key. Here is a list of mathematical constructions made in that manner (these can also be found by choosing Typesetting and Table/Matrix from the Insert menu). ‚ÎêÏ ‚ÎüÏ or ‚Î2Ï ‚Î^Ï or ‚Î6Ï ‚Î_Ï or ‚Î-Ï ‚Î&Ï or ‚Î7Ï ‚Î+Ï or ‚Î=Ï

Go to the numerator of a fraction to be written or to the denominator of a fraction whose numerator is already written Go into a square root Go to the superscript position He.g., of a powerL

Go to the subscript position He.g., of a variable or derivativeL

Go to the overscript position He.g., of a sum, product, or integralL

Go to the underscript position He.g., of a sum, product, integral, or limitL

‚Î%Ï or ‚Î5Ï

Go from superscript position to subscript position or vice versa, or from overscript position to underscript position or vice versa, or from the root position to the exponent position or vice versa

‚Î,Ï

Add a column to a table or matrix

‚οÏ

Add a row to a table or matrix

‚ÎâÏ

Return from a special position

‚Î.Ï

Select the next larger subexpression

Chapter 3 • Notebooks

77

The symbols ‚Î/Ï mean that we hold down the ‚ key while pressing /. The symbol ¿ means the return key, and â means the space key. Some constructions can be made in two ways. The first way mentioned should be possible with most keyboards, whereas the second should work with any keyboard. If both work with your keyboard, choose the way you feel more comfortable with or that is easier for you to remember. In formulas, we can move the cursor with the arrow keys (, Ø, Æ, and ). To go to the next selection placeholder (É), press Í.

To form derivatives, integrals, sums, and products, we need the characters , Ÿ, „, ⁄, and ¤ („ is a special differential used in integrals). They can be written by enclosing pd, int, dd, sum, and prod between two  keystrokes (see Section 3.3.2, p. 75). Use ‚ÎâÏ to get out of the denominator of a fraction, to get out of a square root, to get down from a power, to get to the baseline from an index, and so on. ‡ Examples

The following are simple examples of writing 2D formulas with the keyboard: To write

aêb

in the form

type

a ‚Î ë Ï b ‚ÎâÏ

a b

[email protected]

‚Î2Ï a ‚ÎâÏ

a 2

x^2

x

x ‚Î ^ Ï 2 ‚ÎâÏ

[email protected]

xn ê x

x ‚Î_Ï n ‚ÎâÏ

xbar

x ‚Î & Ï _ ‚ÎâÏ

Next are more elaborate constructs: To write

in the form

x Ha + b xL

[email protected] + b x, xD

type

Âpd ‚Î_Ï x ‚ÎâÏ Ha + b xL

Ÿ Ha + b xL „ x Âint ‚Î + Ï c ‚Î % Ï d ‚ÎâÏ Ha + b xL Âdd x d

[email protected] + b x, 8x, c, d
c

[email protected] ^ i, 8i, 0, n
⁄ni=0 xi

88a, b, c<, 8d, e, f<< [email protected], x § 0<, 81, x > 0<
Âsum ‚Î + Ï i = 0 ‚Î % Ï n ‚ÎâÏ x ‚Î ^ Ï i ‚ÎâÏ

a b c d e f 0 1

x§0 x>0

Ia ‚Î, Ï b ‚Î, Ï c ‚Î¿Ï d Í e Í f ‚ÎâÏ M

Âpw 0 ‚Î, Ï x § 0 ‚Î¿Ï 1 Í x > 0

Note that parentheses are needed around the expression to be differentiated, integrated, or summed if the expression is in the form of a sum. Note also that we have shown one way to write the expressions, but often we have several possibilities. For example, to write

a+b c+d

, we can first press ‚Î/Ï and then fill in the numerator and denominator.

We can also first write a + b, then press ‚Î.Ï two times to select the numerator, then press ‚Î/Ï, and lastly type the denominator.

78

Mathematica Navigator

Remember that matrices of size 22 can be formed with the BasicMathInput palette. A handy way to create matrices is to use Insert @ Table/Matrix. In the appearing dialog box, ask for a matrix, and then enter the number of rows and columns. We get a blank matrix: K

Ñ Ñ Ñ O Ñ Ñ Ñ

By pressing Í, we can then go through the matrix and enter the elements. If we ask for a table, the result does not have the parentheses. Writing 2D formulas is easier than it seems to be when looking at the previous ‚ and  key sequences. Indeed, Mathematica’s way of writing formulas is one of the best and easiest in the market, if not the best and easiest. Try it.

3.4 Writing Mathematical Documents 3.4.1 Introduction ‡ Mathematica as a Writing Tool

As noted in Section 3.1.2, p. 54, Mathematica is an advanced environment for technical writing. One of the advantages of using Mathematica as a writing tool is that the whole document can be prepared with just one application. For example, graphics can be created with Mathematica, and Mathematica writes the results of mathematical computations in a form ready to be printed. Writing and computation take place in the same application so that they have a fruitful interaction: When writing the text, you may observe new needs for mathematical computation, and from the results, you may observe new things to be reported. In addition, the properties of Mathematica needed for using Mathematica as a writing environment are of high quality. For example, with Mathematica we get first-rate •text layout by using styles and style sheets (Section 3.1.2, p. 54); •formulas by using the traditional form (Sections 3.4.2, p. 80, and 3.4.3, p. 86); •graphics of PostScript form (Chapters 5 through 8); •tables with many kinds of fine-tuning (Chapter 15); • indexes with hyperlinks (see Author Tools, p. 79); and • Help Browser material with hyperlinks (see Author Tools, p. 79). Furthermore, Mathematica, as one of the most powerful mathematical systems available, helps you with all kinds of computations needed to prepare your document. Mathematica documents can also be converted into LATEX, HTML, PDF, RTF, and PS documents from File @ Save As…. Whereas text layout, graphics, and tables are considered elsewhere, in Sections 3.4.2 through 3.4.4 we present some other material that is helpful to know when using Mathematica as a writing tool. In particular, we show how to write mathematical formulas and how to number formulas and sections automatically. ‡ Selecting a Style Sheet

The key to writing with Mathematica is the use of styles (Section 3.1.2, p. 54). With styles, you can easily write titles, headings, text, and formulas. Styles help in getting a consistent look throughout the document.

Chapter 3 • Notebooks

79

Remember that the styles of cells vary according to the style sheet you use (see Section 3.1.2). You may start the writing work with the Default style sheet, but at some point you should consider the style sheet in more detail. Regarding equation numbers, with all style sheets we can get simple equation numbers such as (7) with the DisplayFormulaNumbered style. Structured equation numbers such as H2.7L can be obtained by using the EquationNumbered style with the Textbook style sheet (see Section 3.4.4, p. 90). After choosing a style sheet, you may want to modify it (see Section 3.2.2, p. 63). ‡ Main and Working Documents

When writing a mathematical document with Mathematica, it may be useful to work simultaneously with two documents: a main document and a working document. The main document will grow into the final publication, whereas all computations are done in the working document. Mathematical results, tables, and graphics are copied from the working document into the main document. This division into two documents may be needed because the main document may not contain the Mathematica commands but only the results. The working document contains all used Mathematica commands so that all computations can easily be done again. The working document should include the same sections as are in the main document so that you can easily find the computations of a certain section. Add into the working document comments about the computations, such as any difficulties that may arise; they may be valuable if you need to do similar computations at a later time. When you have completed the writing project, you will then have the main document ready to be printed and the working document that will enable you to redo and modify computations as needed. ‡ Author Tools

In preparing a long, possibly book-sized document, and adding documents into the Help Browser, the add-on package AuthorTools may be very valuable. With the author tools, we can do the following: •create a table of contents with hyperlinks; •add index entries into the document; •create an index with hyperlinks; •create a Browser Categories file (for adding information into the Help Browser); and •create a Browser Index file (to add the index entries into the Master Index of the Help Browser). With this package, we can also compare differences among notebooks; restore corrupted notebooks; create bilaterally formatted cells (for displaying examples of Mathematica calculations); extract all cells of a particular type and save them in a desired format; insert objects to display the current values of variables such as the date, time, and the file name; and set printing options such as headers and footers. Each of these operations can be done either on a single notebook or on a set of notebooks. For example, we can generate a unified index or table of contents for a book consisting of several notebooks. We used the package in the writing of this book to add the index entries, to create an index, and to create the Browser Categories and Browser Index files. Look at http://support.wolfram.com/mathematica/packages/authortools/authortoolsinv6.html for information about the AuthorTools package in Mathematica 6. This page says, “The AuthorTools app pack is included with Mathematica 6, but it is considered legacy code and may not work as well with version 6 as it did in previous versions of Mathematica. It is included to help you during the transition to newer functions and syntax.”

80

Mathematica Navigator

3.4.2 Display Formulas ‡ Styles for Display Formulas

We can distinguish two types of formulas: display formulas and inline formulas. Display formulas are displayed in their own lines of text, whereas inline formulas are written inside normal text. Before explaining how to write display formulas, we consider the styles used for them. To write formulas, each style sheet (except Demonstration) has the styles DisplayFormula and DisplayFormulaNumbered. These styles can be used either directly with Format @ Style or by choosing Format @ Style @ Other… and then typing the name of the style; the latter method has to be used with the Article and Book type style sheets. The Article and Book type style sheets have the styles Equation and EquationNumbered in Format @ Style (other style sheets do not have these styles). The styles DisplayFormula and Equation have some differences in the alignment of the formula. The styles DisplayFormulaNumbered and EquationNumbered have the difference that the former generates simple numbers such as H7L throughout the notebook, whereas the latter generates structured numbers such as H2.7L, where the first number refers to the chapter number and the second number to the formula within that chapter [however, in the JournalArticle style sheet, the EquationNumbered style gives a simple number such as H7L]. Recommendations are as follows. If you want to use structured equation numbers, use the Textbook style sheet and the styles Equation and EquationNumbered (see more details in Section 3.4.4, p. 90). If unstructured equation numbers suffice, use any of the other style sheets and the styles DisplayFormula and DisplayFormulaNumbered (however, with the JournalArticle style sheet, it is easiest to use the styles Equation and EquationNumbered because these are in the style menu). Numbered equations are considered in Section 3.4.4, p. 89. ‡ Writing Display Formulas

To write a display formula (a mathematical formula in a separate line), complete the following simple steps: • Write the formula in the usual Input style by using any of the various ways to write inputs (see write 2D formulas (e.g., ⁄i=1 ai ) with the keyboard or by using the BasicMathInput and

Section 3.3.1, p. 73): Write usual 1D mathematica code (e.g., Sum[Subscript[a, i], {i, n}]) or

n

SpecialCharacters palettes. • You can execute any part of the formula by selecting that part with the mouse and choosing Evaluation @ Evaluate in Place or by pressing ‡÷Á (Ì÷Á on a Macintosh). • Transform the formula into the traditional mathematical form by letting the cursor be in the formula and choosing Cell @ Convert To @ TraditionalForm or by pressing ˜÷‚ÎtÏ (˜÷ÌÎtÏ on a Macintosh). Lastly, choose, from Format @ Style, the cell style to be one of DisplayFormula, DisplayFormulaNumbered, Equation, or EquationNumbered. Sometimes you may want to nudge some parts of a formula. For example, to nudge to the left, press ‚ÎÏ several times. Another way to nudge is the use of the menu commands, found in Insert @ Typesetting. To write an inline formula (a mathematical formula among text), see Section 3.4.3, p. 86.

Chapter 3 • Notebooks

81

‡ Example 1

Suppose we want to write the following formula: fn = ‡

p sinHxL

n+x

0

„ x, n = 1, 2, …

First, we write the following input:

[email protected], nD = [email protected]@xD ê Hn + xL, 8x, 0, p
Then we transform the cell into traditional form: fn = ‡

0

p sinHxL

n+x

‚x

Lastly, we transform the cell into the Equation style: fn = ‡

p sinHxL

0

n+x

„x

We can write “n = 1, 2, …” at the end. Note that here we showed the formula in three separate forms in three cells to show how the formula proceeds, but normally the conversions are done in only one cell. ‡ Comment

The previous method of writing formulas works but has the restriction that the formula to be written has to follow correct Mathematica syntax; otherwise, the transformation into traditional form does not succeed. For example, we cannot write “n = 1, 2, …” at the end of the input: [email protected], nD = [email protected]@xD ê Hn + xL, 8x, 0, p
This input simply does not transform into the traditional form. Therefore, often we have to afterwards add some minor components such as “n = 1, 2, …” into the formula. Next, we present a modified way to write formulas; I have been comfortable with this way. ‡ Using a Template

Now we present a way to write formulas in which we first prepare a template for a formula. Each time we would like to write a formula, we take a copy of this template and then write the formula. Thus, first prepare a template as follows: • Write template in the Input style. • Transform the cell into the traditional form by letting the cursor be in the input and choosing Cell @ Convert To @ TraditionalForm or by pressing ˜÷‚ÎtÏ (˜÷ÌÎtÏ on a Macintosh). • Choose, from Format @ Style, the cell style to be one of DisplayFormula, DisplayFormulaNumbered, Equation, or EquationNumbered. The result of these steps is a template like the following: template

82

Mathematica Navigator

We can hold the template at the end of our document or in a separate notebook. Now, each time we want to write a formula, we take a copy of this cell, remove “template”, and write a new formula. In writing, we can use palettes or write 2D formulas directly with the keyboard. We can also use Mathematica commands such as Integrate, but then we have to again transform the formula into the traditional form. In this method, the formula need not be in the correct Mathematica syntax. On the other hand, if we now want to execute a part of the formula, we get the warning that the traditional form has some restrictions in mathematical interpretation. ‡ Example 2

We want to write the same formula as in Example 1. We take a copy of the template and, with the aid of BasicMathInput palette or the keyboard, write the formula. It comes ready without any transformations: fn = ‡

0

p sinHxL

n+x

„ x, n = 1, 2, …

In writing the formula, do not type any spaces because the traditional form automatically writes spaces at suitable places. ‡ Example 3

Next, we want to write the following formula, which is a special case of the formula we considered in Examples 1 and 2: f1 = CiH1L sinH1L - CiH1 + pL sinH1L + cosH1L H-SiH1L + SiH1 + pLL

Copy the formula we wrote in Example 2, delete “n = 1, 2, …”, and replace n with 1: f1 = ‡

0

p sinHxL

1+x

„x

Select the integral and choose Evaluation @ Evaluate in Place. ‡ Example 4

Now we want to write this formula: ‡

p sinHxL

0

n+x

„ x = CiHnL sinHnL - CiHn + pL sinHnL + cosHnL HSiHn + pL - SiHnLL

Because we now want to use an assumption, we write Mathematica code: [email protected]@xD ê Hn + xL, 8x, 0, p 0D

Execute the right-hand side by pressing ‡÷Á:

[email protected]@xD ê Hn + xL, 8x, 0, p
Convert this into traditional form and equation: ‡

0

p sinHxL

n+x

„ x = CiHnL sinHnL - CiHn + pL sinHnL + cosHnL HSiHn + pL - SiHnLL

Chapter 3 • Notebooks

83

‡ Example 5

To write the formula, d =‡

1

log HxL 7

0

1

=-

„x

1 - x2 p 9275 p6 logH4L + 133 p4 Alog H4L + 12 zH3LE + 21 p2 Alog H4L + 120 zH3L log H4L + 720 zH5LE + 3

5

2

3 Alog H4L + 420 zH3L log H4L + 15 120 zH5L log H4L + 10 080 zH3L logH4L + 90 720 zH7LE= = -5040.39 768

7

4

2

2

so that the equal signs are aligned, first write as follows:

d = [email protected]@xD ^ 7 ê [email protected] - x ^ 2D, 8x, 0, 1
Then execute separately the second and the third integral:

d = [email protected]@xD ^ 7 ê [email protected] - x ^ 2D, 8x, 0, 1
21 p2 [email protected] + 120 [email protected] [email protected] + 720 [email protected] +

3 [email protected] + 420 [email protected] [email protected] + 10 080 [email protected] [email protected] + 15 120 [email protected] [email protected] + 90 720 [email protected] = -5040.389239250824`

Convert this to traditional form and equation: d =‡

1

log HxL

0

-

7

„x =

1 - x2 1

768

p I275 p6 logH4L + 133 p4 Ilog H4L + 12 zH3LM + 21 p2 Ilog H4L + 120 zH3L log H4L + 720 zH5LM + 3

5

2

3 Ilog H4L + 420 zH3L log H4L + 15 120 zH5L log H4L + 10 080 zH3L logH4L + 90 720 zH7LMM = -5040.39 7

4

2

2

To fine-tune the formulas, add a return character before the second and third equal signs, write an alignment marker (ÂamÂ) before each equal sign, write a no break sign (ÂnbÂ) after the third equal sign, select the cell bracket, and choose Format @ Text Alignment @ On AlignmentMarker. Lastly, replace some usual parentheses with brackets ([ ]) and curly braces ({ }) to make the formula more readable. ‡ Example 6

Next, we write the following formula: a ‡ x „x =

xa+1 , a+1

a  -1,

logHxL,

a = -1.

To begin, write the integral with the template:

84

Mathematica Navigator

a ‡ x „x =

Then write and execute the following command: xa+1 PiecewiseB:: xa+1

a+1

, a != -1>, [email protected], a == -1<>F êê TraditionalForm

a  -1

a+1

logHxL

a  -1

Copy this result and paste into the previous formula: a ‡ x „x =

xa+1 a+1

a  -1

logHxL

a -1

Lastly, select the cell bracket of the formula and choose Insert @ Typesetting @ Add Frame or click the † button in the BasicTypesetting palette. If the frame seems to be too thick, select the cell bracket of the formula and, with the Option Inspector, change the value of BoxFrame to, for example, 0.25: a ‡ x „x =

xa+1 a+1

a  -1

logHxL

a = -1

Previously, we wrote the piecewise definition as a Mathematica command. Another way to write the formula is to write directly a 2D formula. Take a copy of the template we created previously, paste it, and write, using the BasicMathInput palette or direct 2D input, as follows: a ‡ x „x =

xa+1 a+1

a  -1

logHxL a = -1

Here, to begin the piecewise definition, type ÂpwÂ. To create slots for the four parts of the definition, type ‚Î,Ï. Fill in the slots. To align the columns left, select the cell bracket of the formula, and using the Option Inspector, set the value of the GridBoxAlignment option to {"Columns" -> {{Left}}}. To fine-tune the formula, type a comma or period at suitable places. If you want to adjust the frame (thickness, margins, background, etc.), select Format @ Option Inspector, go to Formatting Options @ Expression Formatting @ Specific Box Options @ FrameBoxOptions, and set the values of suitable options. ‡ Example 7

To write the formula, a lim

xض

x

+1

= ‰a

x

use the BasicMathInput palette or direct 2D input. First, click the ‡ button in the palette, and write lim Ñ

into the upper box and x Ø ¶ into the lower box. Then, write the rest of the formula. Another way is to write a Mathematica command: [email protected] + a ê xL ^ x, x Ø ¶D = [email protected] + a ê xL ^ x, x Ø ¶D

Execute the right-hand side, and convert the cell to traditional form and equation.

Chapter 3 • Notebooks

85

‡ Example 8

To write this one, 11110000 k

n

use the template we created previously and click É two times from the BasicMathInput palette to get Ñ

three placeholders. Write “1 1 1  1” in the first box; write Ââââ between each character. The three dots  can be found from the SpecialCharacters palette under Textual Forms. Type ß from the same palette in the second box, and k in the last box. Copy this whole expression, paste it next to the expression, and replace the 1’s with 0’s and k with n. ‡ Example 9

To write the matrix  a1 n  a2 n

a11 a21

a12 a22

ª am 1

ª ª am 2  am n

paste a copy of the template we created previously and insert a H4 μ 4L empty matrix with Insert @ Table/Matrix @ New…. Then fill in the elements. The characters  (center ellipsis) and ª (vertical ellipsis) can be found from the SpecialCharacters palette under Textual Forms. Note that for the elements in the last row, we have to type a space between the indices to get m and n italicized. The space between the indices in the last column and last row may not satisfy you. To get the indices closer to each other, write an invisible comma between the indices with Â,Â. In this way, we get the following matrix:  

a11 a21

a12 a22

a1n a2n

ª am1

ª ª am2  amn

‡ Example 10

With the BasicMathInput palette, we can write expressions such as x and x. With the BasicTypesetting ` ° – è palette, many other similar expressions can be written: x† , x+ , x+ , x- , x- , x, x, x, x* , x* , x£ , x , x, x, x, and x. Ñ

Ñ

Still more similar expressions can be written by clicking the buttons ‡Ñ , ‡Ñ , ‡ÑÑ , Ñ ‡, Ñ ‡, ‡, ‡, or ‡ in the Ñ

Ñ

BasicTypesetting palette and filling the slots with suitable characters. Recall (Section 3.3.3, p. 76) that Ñ

the constructions ‡Ñ , ‡Ñ , ‡, and ‡ can also be written with the keyboard by typing ‚Î^Ï, ‚Î_Ï, ‚Î&Ï, Ñ

or ‚Î+Ï, respectively. In addition, we have the following characters, familiar from matrix calculus: (ÂcoÂ), (ÂtrÂ), æ (ÂctÂ), and  (ÂhcÂ) (they are written without the ‡Ñ construct).

86

Mathematica Navigator

3.4.3 Inline Formulas ‡ Writing Inline Formulas

An inline formula is among the text of a Text-style cell. Such formulas are often small, such as i, ai , x, f HxL, f £ HxL,  f ë x,

f x

,

2 x , sinHxL, a ê b, , limxض J1 + x N = ‰x , Ÿ sinHxL „ x, Ÿo cosHxL „ x, or ⁄¶ i=1 1 ë i . If the a

a x

p

b

formula is larger, it is often more useful to put it in a separate line as a display formula. Note that Mathematica formats inline formulas lower as display formulas (as is usual in traditional mathematical notation). For example, in a fraction, the font size is smaller; in a limit, the variable and limiting value are written as a subscript next to “lim”; and in a definite integral or sum, the lower and upper limits are written as sub- and superscripts (and not as under- and overscripts). To write an inline formula, we begin and end the formula with the special key combinations ‚÷Î(Ï and ‚÷Î)Ï. The simple steps are as follows: •Begin the formula by typing ‚÷Î(Ï or ‚÷Î9Ï. •Write the formula. •End the formula by typing ‚÷Î)Ï or ‚÷Î0Ï. The formula can be written in any way: linearly, in a 2D form with the keyboard (see Section 3.3.3, p. formulas such as [email protected] ê H1 + xL, xD can be transformed into the traditional form by selecting the 76), or in a 2D form with the palettes. 2D formulas are automatically in the traditional form. Linear 1D

formula with the mouse and choosing Cell @ Convert To @ TraditionalForm or pressing ˜÷‚ÎtÏ (˜÷ÌÎtÏ on a Macintosh). I often write the simplest formulas (e.g., variables, special characters, subscripts, powers, functions, square roots, and fractions) with the keyboard and less simple formulas (e.g., integrals and sums) with palettes. Note that a part of an inline formula can also be executed by selecting that part and then choosing Evaluation @ Evaluate in Place or by pressing ‡÷Á (Ì÷Á on a Macintosh). However, this may seldom be needed because inline formulas are, as a rule, simple. ‡ Example 1

We want to write a simple text cell: Assume that x is positive. Then… Just begin a Text cell by pressing ‡Î7Ï, write the text before x, then write ‚÷Î(Ï x ‚÷Î)Ï, and continue the text. Note that you need not worry about italicizing the variable; Mathematica does it for you. Another way to write x is to press ‚÷ÎiÏ x ‚÷ÎiÏ to italicize the variable. Choose the way you find easiest. I consistently use ‚÷Î(Ï … ‚÷Î)Ï for all inline formulas, even formulas as simple as x. ‡ Example 2

Next, we want to write the following text cell:

Consider the function f HxL = a sinHx + pL. Let…

Chapter 3 • Notebooks

87

To write the formula, press ‚÷Î(Ï, write f(x)=aâsin(x+ÂpÂ), press ‚÷Î)Ï, and continue the text. Note that when writing the formula you should not press the space key in any other place besides in multiplications; Mathematica adds suitable spaces when needed (e.g., before and after = or +). ‡ Example 3

Now, we write the following text cell: Let f HxL =

a x

and assume that…

To write the formula, do one of the following: •Use the keyboard: ‚÷Î(Ï f(x)=a ‚÷Î/Ï x ‚÷Î)Ï (see Section 3.3.3, p. 76). a

•Use the BasicMathInput palette to write the fraction: ‚÷Î(Ï f(x)= x ‚÷Î)Ï. •Write the formula linearly as ‚÷Î(Ï f(x)=a/x ‚÷Î)Ï, select a/x, and press ˜÷‚ÎtÏ. ‡ Example 4

Let us now write the following formula in the text cell: If the integral Ÿ0 f HxL „ x converges, then… ¶

Do one of the following: •Use the keyboard to write the lower and upper bounds of the integral as sub- and superscripts: ‚÷Î(Ï Âint ‚÷Î_Ï 0 ‚÷Î%Ï Âinf ‚÷ÎâÏ f(x) Âdd x ‚÷Î)Ï. (This is easier than it looks; try it.)

•Use the BasicInput palette to write the integral: ‚÷Î(ÏŸ0 f HxL „ x‚÷Î)Ï (go with Í from one selection ¶

placeholder to the next one). •Write the formula linearly as ‚÷Î(ÏIntegrate[f[x],{x,0,Infinity}]‚÷Î)Ï, select the formula, and press ˜÷‚ÎtÏ. ‡ Example 5

Now we want to write the following: Because Ÿ

1 a+x2

1

„x =

tan-1

a

x

, then…

a

First, write the following with the BasicMathInput palette: Because Ÿ

1 a+x2

„x = Ÿ

1 a+x2

„ x, then…

Select the latter integral and execute it with ‡÷Á. Here is the result: Because Ÿ

x

tan-1 1 a+x2

a

„x =

, then…

a

To make the formula lower, cut the denominator, insert a fraction after the equal sign, write 1 into the numerator, and paste the cut square root into the denominator: Because Ÿ

1 a+x2

„x =

1 a

tan-1

x a

, then…

88

Mathematica Navigator

In this way, you can also modify the results Mathematica gives. ‡ Example 6

The following is another way to write the same formula: Because Ÿ

1 a+x2

„ x =, then…

Then execute the integral:

[email protected] ê Ha + x ^ 2L, xD F

x

ArcTanB

a

a

Copy the result into the formula: Because Ÿ

ArcTanB 1 2

a+x

F

x a

„x =

, then…

a

Select the value of the integral, convert it into traditional form, and then move the denominator as shown previously. In this way, results from calculations can be inserted into inline formulas. ‡ Example 7

In display formulas, the default is that constructs such as a sum, product, union, intersection, lim, max, or min are written in a tall form: ‚ ai + Ê ci + lim f HxL + max 8di < n

n

i=1

i=1

xØ0

i

However, in an inline formula the default is that these constructs are displayed in a low form: ⁄i=1 ai + ‹i=1 ci + limxØ0 f HxL + maxi 9di = n

n

This is a very useful property. However, we have an option, LimitsPositioning, that also enables us to get tall forms in inline formulas. This option can be found from the Option Inspector when the View is set to be alphabetically. In the Option Inspector, we can see that the option can be used in underscriptÑ

Ñ

boxes ‡, overscriptboxes ‡, and underoverscriptboxes ‡. If we select the cell bracket of the previous Ñ

Ñ

formula and set, with Option Inspector, LimitsPositioning (UnderscriptBoxOptions) to be False, the lim and max constructs become tall: ⁄i=1 ai + ‹i=1 ci + lim f HxL + max 9di = n

n

xØ0

i

If we set LimitsPositioning (UnderoverscriptBoxOptions) to be False, the sum and union become tall: ⁄ ai + ‹ ci + limxØ0 f HxL + maxi 9di = n

n

i=1

i=1

If we set both LimitsPositioning (UnderscriptBoxOptions) and LimitsPositioning (UnderoverÖ scriptBoxOptions) to be False, all constructs become tall:

Chapter 3 • Notebooks

89

⁄ ai + ‹ ci + lim f HxL + max 9di = n

n

i=1

i=1

xØ0

i

3.4.4 Automatic Numbering ‡ Introduction

Sections and some formulas in a mathematical document are often numbered so that we can easily refer to them. Often, we also want to refer to some page numbers of our document. With Mathematica, we can give the numbers manually and also write references to them manually, but we can also let Mathematica automatically choose the appropriate numbers. In a small document, the numbers of sections and references to page numbers can easily be written manually, and to some extent the same is true for formulas. However, in a larger document the automatic numbering becomes more tempting because chances increase that sections and formulas are moved to other places and new sections and new formulas are written among old ones. After such a modification, automatic numbers and references to them are again correct without your having to manipulate them in any way, whereas manually given numbers and references to them have to be manually corrected. However, using the automatic numbering system of Mathematica often requires some work in the form of handling so-called cell tags. Next, we consider automatic numbering of pages, formulas, and sections. ‡ Referring to Page Numbers

Suppose you want to write “According to Theorem 2.3 (see p. XXX) …”, where XXX should be replaced with the correct page number. First, you have to assign a cell tag to the cell that contains Theorem 2.3. Select the cell bracket of the theorem, and do the following: •Choose Cell @ Cell Tags @ Add/Remove Cell Tags…; the following window appears:

•Write a name (e.g., Theorem 2.3) for the cell into the Cell tag field and click Add. To create a reference to the page number of Theorem 2.3, put the cursor in the place where you want to refer to the theorem (i.e., after “see p. ”) and do the following:

90

Mathematica Navigator

•Choose Insert @ Automatic Numbering…; the following window appears:

•Set Counter to be Page. •From the list All cell tags in the notebook, click the cell tag of the theorem, and click OK. The page number now appears, at the location of the cursor, in the form XXX. When the document is printed, XXX is automatically replaced with the correct page number. Before printing, you can see the correct page number by choosing File @ Printing Settings @ Show Page Breaks. The page number also has the useful property that when it is clicked on, the document is scrolled to the cell to which the page number refers. By the way, a list of all cell tags of the current notebook can be seen by choosing Cell @ Cell Tags @ Find Cell Tag. By selecting a cell tag from the list, the notebook is scrolled to the corresponding cell. The cell tags can be seen in the notebook by choosing Cell @ Cell Tags @ Show Cell Tags. ‡ Manual Numbering of Formulas

Before explaining the automatic numbering of formulas, we show how to manually add a number to a formula. First, write the formula (see Section 3.4.2, p. 80): f =a+bx Add the formula number as a cell frame label as follows. Select the cell bracket of the formula, choose Format @ Option Inspector, set View to be alphabetically, and find the option CellFrameLabels. The default value of this option is {{None, None}, {None, None}}. Replace the second None with “(3.1)“ and press Á. The formula now has the given number: f =a+bx

(3.1)

‡ Automatic Numbering of Formulas

3.4.2, p. 80. To repeat, if you want to use structured equation numbers such as H2.7L, use the Textbook All style sheets (except Demonstration) have styles for automatically numbered formulas; see Section

style sheet and the styles Equation and EquationNumbered. If unstructured equation numbers such as H7L suffice, use any of the other style sheets and the styles DisplayFormula and DisplayFormulaNumbered (however, with the JournalArticle style sheet, it is easiest to use the styles Equation and EquationNumbered because these are in the style menu). The automatic numbers of formulas are useful because they automatically change if we add or remove formulas.

Chapter 3 • Notebooks

91

To create a formula with an unstructured number, first write a formula, then select the cell bracket of the formula, and choose the style to be DisplayFormulaNumbered:

f =a+bx

(1)

To create a formula with a structured number, use the Textbook style sheet. The first number, such as 2 in H2.7L, refers to a chapter. Thus, you have to compose the document by chapters. Each chapter may contain sections, subsections, etc. For each chapter, you have to create, with the BookChapterNumber style, a cell containing the number of the chapter. Of course, it is also useful to create a chapter title; use the BookChapterTitle style. These two styles are not listed in the style menu, so choose Format @ Style @ Other… and type the name of the style. If you would like to remove the number of an equation, just choose the style of the cell to be DisplayFormula or Equation. ‡ Referring to Numbered Formulas

To be able to refer to a numbered formula, we have to first assign a cell tag to the formula. Select the cell bracket of the numbered formula, and do the following: •Choose Cell @ Cell Tags @ Add/Remove Cell Tags…. •Write a name for the formula into the Cell tag field and click Add. To create a reference to a numbered formula, put the cursor in the place where you want to refer to the numbered formula, and do the following: •Write the opening parenthesis ( and choose Insert @ Automatic Numbering…. •Set Counter to DisplayFormulaNumbered (or EquationNumbered) •From the list All cell tags in the notebook, click the cell tag of the formula, click OK, and write the closing parenthesis ). The number of the formula now appears at the location of the cursor. This reference automatically changes if the number of the formula changes. By clicking the number, the notebook is scrolled to where the formula is located. ‡ Modifying Automatic Numbers of Formulas

In the Textbook style sheet, the working of the numbering of formulas is based on chapters. However, you may want to create numbers where the first part is based on, for example, sections. Do as follows. Set the style sheet to be Textbook and choose Format @ Edit Stylesheet…. From Choose a style to modify select Section, choose Format @ Option Inspector…, and find the option CounterAssignments. Its value is a list. Add the element {"EquationNumbered", 0} into the list. In

this way, we tell that the counter for equations is reset to zero at the beginning of each section. From Choose a style to modify select EquationNumbered, choose Format @ Option Inspector…, and find the option CellFrameLabels. In its value, replace CounterBox["BookChapterNumber"] with CounterBox["Section"]. In this way, we tell that the first number for an equation should be the number of the current section (and not the current chapter). ‡ Automatic Numbering of Sections

Manual numbering of sections is, of course, very easy: Just write a suitable number at the beginning of the heading of the section. With automatic numbering, however, we have the advantage that the numbers of sections and references to them are correct after modifications in the order of the sections. To give an automatic number to a section, place the cursor at the beginning of the section heading and do the following:

92

Mathematica Navigator

•Choose Insert @ Automatic Numbering…. •Set Counter to be Section and click OK. If you want an automatic number for a subsection, such as 2.4, first create the number 2 of the section in the way we showed previously, type a period, and then create the number 4 of the subsection in the same way (just set Counter to Subsection). Similarly, we can create numbers for sub-subsections. To make creating section numbers easier, you can create a notebook having one section, one subsection, and one sub-subsection with automatic numbers. Then copy a suitable heading from this notebook each time you would like to start a new section. ‡ Referring to Numbered Sections

Suppose we want to write “In Section X we have shown…”, where we want, in place of X, the correct section number to appear. In that section, we have a certain cell to which we want to refer. To write such a reference, first assign a cell tag to the corresponding cell: Select the cell bracket, choose Cell @ Cell Tags @ Add/Remove Cell Tags…, write a name for the cell, and then click Add. A reference to the cell is then written in the same way a reference is written for a numbered equation: Choose Insert @ Automatic Numbering…, set Counter to Section, click the cell tag of the cell in question, and click OK. To write a reference to a cell in a subsection, first assign a cell tag to that cell. To write a reference such as “In Subsection X.Y we will show that…”, first create the section number X with Insert @ Automatic Numbering… as above, type a period, and then, in the same way, create the subsection number Y. Likewise, we can create a reference to a sub-subsection. ‡ Automatic Numbering of Figures, Tables, etc.

To create automatic numbers for figures and tables, first choose a style sheet having the styles Figure and Table; such style sheets are among the Article and Book type style sheets. After you have created a figure, select its cell bracket and set its style to be Figure. Create a caption below the figure by choosing the FigureCaption style and writing the caption. In the caption, create an automatic number for the figure by choosing Insert @ Automatic Numbering…, setting Counter to be Figure, and clicking OK. After you have created a table, select its cell bracket and set its style to be Table. Create a title below the table by choosing the TableTitle style and writing the title. In the title, create an automatic number for the table by choosing Insert @ Automatic Numbering…, setting Counter to be Table, and clicking OK. To refer to a figure or table, first create a cell tag to the corresponding cell. Then choose Insert @ Automatic Numbering…, set Counter to be, for example, Figure, click the cell tag, and click OK. In the same way we can use automatic numbers for pictures and programs, for example.

4 Files Introduction 93 4.1 Loading Packages 94 4.1.1 Standard Packages 94 << 4.1.2 Forgetting to Load 96 4.1.3 Other Packages and Add-Ons 97 $BaseDirectory, $UserBaseDirectory 4.2 Exporting and Importing 100 4.2.1 Exporting and Importing Data 100 Export, Import, $ExportFormats, FilePrint, etc. 4.2.2 Exporting and Importing Graphics 105 Export, Import, $ExportFormats, etc. 4.2.3 Locating the File 107 Directory, $Path, SetDirectory, ResetDirectory, FileNames 4.3 Saving for Other Purposes 109 4.3.1 Continuing Work in Later Sessions 109 >>, <<, Save, >>>, DumpSave 4.3.2 Exporting to TeX, C, Fortran, and HTML 111 TeXForm, CForm, FortranForm, MathMLForm 4.4 Managing Time and Memory 112 4.4.1 Managing Time Consumption 112 Timing, TimeConstrained, TimeUsed, DateList, etc. 4.4.2 Managing Memory Consumption 113 ByteCount, MaxMemoryUsed, MaxMemoryUsed, Share, etc.

Introduction The world’s greatest and most powerful computer was constructed, so mathematicians decided to test it out by seeing if it could make any impression on some classical unsolved problems. They decided on Fermat’s last theorem (this happened prior to the work of Andrew Wiles), namely that xn +yn = zn has no solutions over the natural numbers for n ¥ 3. For days they fed it with every known piece of information, conjecture, and partial result, and at last they set it to work. After a few minutes it printed out: “I have a wonderful proof of this result, but my memory is too small to store it.” Note that you may skip this chapter if you right now do not need (or already know how) to do the following: • use the packages of Mathematica; • read data or graphics from a file; • write data or graphics into a file; • save results for later use; • convert results and notebooks for TeX, HTML, C, or Fortran; • speed up calculations; or • save memory consumption.

94

Mathematica Navigator

With packages we can give added functionality to Mathematica. Section 4.1 describes various types of packages, their loading, and what to do if we forget to load a package. Read Section 4.2.1 if you have data in a file and you want to visualize or analyze it with Mathematica by, for example, using some plotting commands or some statistical methods. You then need to import the data in such a way that Mathematica understands it. This means that you must form lists that contain the elements of the data. We consider here some simple examples, but real-life data are considered, for example, in Chapter 10. Data can also be exported for use in other applications. You may want to export a Mathematica plot to another application or to import into Mathematica a plot made by another application. Section 4.2.2 is devoted to these topics. In Section 4.3, we consider saving and loading results. This may be useful if we want to continue calculations in later sessions. We also consider converting Mathematica notebooks and results to the forms required by TeX, HTML, C, and Fortran. In Section 4.4, we show some ways to manage and save computing time and computer memory.

4.1 Loading Packages 4.1.1 Standard Packages ‡ Types of Packages

Mathematica packages supplement the kernel by providing more commands. We have several types of packages. To see the types of packages, write as follows: [email protected]$InstallationDirectory <> "êAddOns"D; [email protected]"*Packages"D 8ExtraPackages, LegacyPackages, Packages<

The directory Packages contains the standard packages (or the standard extra packages, as they also are called) of Mathematica 6. In ExtraPackages we have a few extra packages. LegacyPackages contains the packages of Mathematica 5.2; note that they are now obsolete. Much of the functionality of the legacy packages has been included in the ordinary Mathematica 6, and for much of the functionality of the legacy packages that has not been included in the ordinary Mathematica 6, we have new packages. Let us look at the various packages in more detail. ‡ Standard Packages

A list of the standard packages can be seen by clicking, in the home page of the Documentation Center, the Standard Extra Packages hyperlink. The resulting page has hyperlinks to the documentation of the packages. To see the names of all the packages, we could also write as follows: [email protected]$InstallationDirectory <> "êAddOnsêPackages"D; [email protected]

However, we do not show the result here. Instead, we show the packages classified to several groups. Each package shown here is also a hyperlink to the guide page in the Documentation Center. For most packages, the guide page also contains a link to a tutorial page. • Advanced commands: Developer`, Experimental` • Algebra: FiniteFields`, Quaternions` • Calculus: FourierSeries`, VariationalMethods`, VectorAnalysis` • Differential equations: EquationTrekker`, NumericalDifferentialEquationAnalysis` • Discrete mathematics: Combinatorica`, ComputationalGeometry`, GraphUtilities` • Geometry: Polytopes`, PolyhedronOperations`

Chapter 4 • Files

95

• Graphics: BarCharts`, ErrorBarPlots`, Histograms`, PieCharts`, PlotLegends`, VectorFieldPlots`, WorldPlot` • Miscellaneous: Benchmarking`, Calendar` • Music: Audio`, Music` • Notebooks: GUIKit`, Notation`, XML` • Number theory: PrimalityProving` • Numerical mathematics: ComputerArithmetic`, FunctionApproximations`, NumericalCalculus`, Splines` •Physics: BlackBodyRadiation`, Geodesy`, PhysicalConstants`, ResonanceAbsorptionLines`, StandardAtmosphere`, Units` •Statistics: ANOVA`, HierarchicalClustering`, HypothesisTesting`, LinearRegression`, MultivariateStatistics`, NonlinearRegression`, RegressionCommon`, StatisticalPlots` ‡ Using Standard Packages

The packages are not normally loaded when Mathematica is loaded. Instead, we have to take care of loading each package we intend to use. To load a package, do as in the following example: << NumericalCalculus` Load the numerical calculus package

Instead of <<, we can also use the Get command. At the end of the name of a package, we have the backquote or grave accent character ` (this is actually a context mark in Mathematica). Note that after the ` you always have to press the space key so that the accent character appears. We now load the numerical calculus package: << NumericalCalculus`

We can then ask a table of the names defined in the package: ? NumericalCalculus`*

NumericalCalculus` EulerRatio

ExtraTerms

NLimit

NSeries

Terms

EulerSum

ND

NResidue

Radius

WynnDegrÖ ee

[email protected], z -> z0 D numerically finds the limiting value of expr as z approaches z0 . à

By clicking, in the table, a name such as NLimit, we get a short description of that name (as shown previously). To find more information about NLimit, click the à button. At the bottom of the resulting page, we can click the Numerical Calculus Package hyperlink to get a description of the whole package. After loading a package, we can use its commands: [email protected]@xD ê x, x Ø 0D

1.

We can even open a package to look at the code. Just choose Open from the File menu and select a package from $InstallationDirectory <> "/AddOns/Packages". Looking at the code of a package may be interesting if you are wondering how the package works. You can then perhaps even learn something about programming with Mathematica.

96

Mathematica Navigator

‡ Automating Loading

In $UserBaseDirectory, we have a Kernel folder and there an initialization file called init.m. Each time the kernel is started, the commands in the initialization file are executed. So, if you frequently use, for example, the NumericalCalculus` package, write << NumericalCalculus` in the initialization file. Then you can always use the commands of this package without loading it.

4.1.2 Forgetting to Load ‡ Forgetting to Load a Package: Shadowing

Let us see what happens if we forget to load a package. We start a new session and try to use NLimit: [email protected]@xD ê x, x Ø 0D [email protected] NLimitB

, x Ø 0F

x

It did not work because we forgot to load the appropriate package. Note that the NLimit command is blue, indicating that Mathematica does not know about it. So, we try to solve the problem by loading the package: << NumericalCalculus` NLimit::shdw : Symbol NLimit appears in multiple contexts 8NumericalCalculus`, Global`<; definitions in context NumericalCalculus` may shadow or be shadowed by other definitions. à

The package was loaded, but now the NLimit command we previously used became red to remind us that there is a problem with the command. As the message states, we now have two NLimit symbols: the one in the package and the one we (unintentionally) created when trying to use NLimit. One of the two symbols may “shadow” the other~that is, Mathematica has to use one of these symbols and disregard the other. The problem (shadowing) is explained in Section 17.3.2, p. 533. Let us now try NLimit:

[email protected]@xD ê x, x Ø 0D

1.

It worked. If we want to resolve the shadowing problem and get rid of the red color, we can remove our own NLimit: [email protected]`NLimitD

In summary, suppose that we forget to load a package~that is, we use a command of a package before loading the package. If we then load the package, it works but we get the warning about shadowing and the command we have used becomes red. (This is an improvement compared with earlier versions of Mathematica. Previously, if a package was loaded after trying to use one of its commands, the command still did not work.) ‡ Forgetting to Load a Package: Recommendations

How to avoid the problem of shadowing? We simply remove, before loading the package, the command we have tried to use. Here is an example. We start a new session and try again to use NLimit: [email protected]@xD ê x, x Ø 0D [email protected] NLimitB

, x Ø 0F

x

We observe that we forgot to load the package. Before loading the package, we remove the NLimit symbol we have (unintentionally) created:

Chapter 4 • Files

97

[email protected]

Then we load the package: << NumericalCalculus`

Now NLimit becomes black so that we do not have any problems with it. Then we can use NLimit: [email protected]@xD ê x, x Ø 0D

1.

Here is a summary: If you forget to load a package before using one of its commands, do as follows: • remove the name you have tried to use; • load the package; and • use the command of the package again. However, note that even without removing the name, the package works, as we previously saw. Another solution to the shadowing problem is to quit the kernel from Evaluation @ Quit Kernel and then restart the kernel from Evaluation @ Start Kernel (or simply by executing a command), but then we may need to do some calculations again.

4.1.3 Other Packages and Add|Ons ‡ Extra Packages

Here are the extra packages: [email protected]$InstallationDirectory <> "êAddOnsêExtraPackages"D; [email protected] 8DifferentialEquations, Integration, LinearAlgebraExamples, Optimization, StatisticsExamples, Utilities<

Here, DifferentialEquations` , Integration` , Optimization` , and Utilities` actually contain several packages, as follows: • DifferentialEquations`: InterpolatingFunctionAnatomy`, NDSolveProblems`, NDSolveUtilities` • Integration`: NIntegrateUtilities` • Optimization`: MPSData`, UnconstrainedProblems` • Utilities`: CleanSlate`, URLTools` Directories Optimization/Data , LinearAlgebraExamples/Data , and StatisticsExamples/Data contain data files: • Optimization/Data: afiro.mps, ganges.mps, shell.mps, standmps.mps •LinearAlgebraExamples/Data : can__229.psa , cavity01.rua , dwg961b.cua , dwg961b.mtx , dwt_1005.psa , gr_30_30.rsa, nos6.mtx, simplematrix.dat, west0381.mtx, wm1.rra • StatisticsExamples/Data: iris.dat ‡ Using Extra Packages

To load, for example, the NDSolveProblems package, write << DifferentialEquations`NDSolveUtilities`

The package defines the following names:

98

Mathematica Navigator ? DifferentialEquations`NDSolveUtilities`*

DifferentialEquations`NDSolveUtilities` CompareMethods

InvariantErrorPlot

FinalSolutions

InvariantErrorSampleRate

InvariantDimensions

RungeKuttaLinearStabilityFunction

InvariantErrorFunction

StepDataPlot

[email protected], solsD gives the end point solutions sols for the system sys specified as an NDSolveProblem.

By clicking, in the previous table, a name such as FinalSolutions, we get a short description of that name (as shown previously). To get more information about the package, search, in Help @ Documentation Center, Differential Equations package and then click Utility Packages for Numerical Differential Equation Solving. To use the data files in the extra packages, import them into Mathematica. Here is an example (we use the directory notation / of a Macintosh computer; we only show two rows of the file): Hdata = [email protected]"StatisticsExamplesêDataêiris.dat"DL êê Short 885.1, 3.5, 1.4, 0.2<, á148à, 85.9, 3., 5.1, 1.8<<

For Import, see Section 4.2.1, p. 100. ‡ Legacy Packages

If you have used Mathematica 5.2 or earlier versions, note that the old packages, called the legacy packages, are now obsolete. They may work, but they are not documented in Help @ Documentation Center. Much of the functionality of the old packages has been included in the basic Mathematica. For example, LogPlot, earlier in the Graphics`Graphics` package, is now a built-in command. Other packages have been replaced with new packages. For example, the functionality of the old Statistics`ConfidenceIntervals` package is now in the new HypothesisTesting` package. For information about the legacy packages, look at CompatibilityêguideêStandardPackageCompatibilityGuide in the Documentation Center. If we load a legacy package, we get a message telling about the status of the package. For example, << Graphics`Graphics` General::obspkg : Graphics`Graphics` is now obsolete. The legacy version being loaded may conflict with current Mathematica functionality. See the Compatibility Guide for updating information. à

Thus, the package is obsolete. By clicking the à button, we get more information about how to replace the package with new functionality of version 6. Here is another example: << Statistics`ConfidenceIntervals` General::newpkg : Statistics`ConfidenceIntervals` is now available as the Hypothesis Testing Package. See the Compatibility Guide for updating information. à

Thus, the package is replaced by a new package. Again, by clicking the à button, we get more information about how to replace the package with the new package.

Chapter 4 • Files

99

‡ Other Packages and Applications

In addition to the packages that come with Mathematica, you may have additional packages and applications. If you want them to be available for all users, put them in the Applications folder that is located in the $BaseDirectory. For example, on my Macintosh with MacOS X, here is the location: êLibraryêMathematica $BaseDirectory

On a Windows machine, the location may be C:\Documents and Settings\All Users\Application Data\Mathematica. On the other hand, if you want the packages to be available only for you, put them in the Applications folder that is located in the $UserBaseDirectory. For example, on my Macintosh, here is the location: êUsersêheikkiêLibraryêMathematica $UserBaseDirectory

On a Windows machine, the location may be of the form C:\Documents and Settings\username \Application Data\Mathematica. Next, we describe a way to automatically install a palette, style sheet, or package to the correct location. ‡ Automatic Installation of Palettes, Style Sheets, and Packages

If you have a new palette, style sheet, or package that you want to install into the correct location, use File @ Install…. The following dialog opens:

From Type of Item to Install, choose Palette, Stylesheet, or Package. From Source, select the file you want to install. In Install Name, type a suitable name for the palette, style sheet, or package. You can also choose the Default Installation Directory. Finally, click Finish. Style sheets and palettes are put in the SystemFiles folder, which is located in the same directories as the Application folder we considered previously. Style sheets are put in SystemFiles @ FrontEnd @ StyleSheets and palettes in SystemFiles @ FrontEnd @ Palettes.

100

Mathematica Navigator

4.2 Exporting and Importing 4.2.1 Exporting and Importing Data ‡ Export and Import

In Sections 4.2.1 and 4.2.2, we consider Export and Import. These are versatile commands to use for the writing and reading of data and graphics (and other material) in more than 100 formats. Next, we study the export and import formats~that is, file formats to which Mathematica is able to write Mathematica material and file formats from which Mathematica is able to read material into Mathematica. The formats that can be used both in exporting and in importing are (in a Macintosh) as follows: ef = $ExportFormats; if = $ImportFormats; 83DS, ACO, AIFF, AU, AVI, Base64, Binary, Bit, BMP, Byte, BYU, BZIP2, CDF, Character16, Character8, Complex128, Complex256, Complex64, CSV, DICOM, DIF, DXF, ExpressionML, FASTA, FITS, FLAC, GIF, Graph6, GZIP, HarwellBoeing, HDF, HDF5, HTML, Integer128, Integer16, Integer24, Integer32, Integer64, Integer8, JPEG, JPEG2000, JVX, List, LWO, MAT, MathML, MGF, MOL, MTX, MX, NB, NOFF, OBJ, OFF, Package, PBM, PCX, PDF, PGM, PLY, PNG, PNM, PPM, PXR, RawBitmap, Real128, Real32, Real64, RIB, RTF, SCT, SND, Sparse6, STL, String, Table, TAR, TerminatedString, Text, TGA, TIFF, TSV, UnsignedInteger128, UnsignedInteger16, UnsignedInteger24, UnsignedInteger32, UnsignedInteger64, UnsignedInteger8, UUE, WAV, Wave64, WDX, XBM, XHTML, XHTMLMathML, XLS, XML, XYZ, ZIP<

[email protected], ifD

The formats that can only be used in exporting are as follows (in a Windows machine, this list also includes EMF and WMF): 8EPS, FLV, Maya, MIDI, PICT, POV, SVG, SWF, TeX, VRML, X3D, ZPR< [email protected], ifD

The formats that can only be used in importing are as follows: 8ApacheLog, CDED, CUR, DBF, Directory, EDF, GTOPO30, ICO, LaTeX, MBOX, MDB, MPS, MTP, NetCDF, ODS, PDB, QuickTime, RSS, SDTS, SXC, USGSDEM, VCF, XPORT< [email protected], efD

A mathematician or statistician may mainly be interested in reading existing data files into Mathematica and writing Mathematica graphics into files that some other programs can use. Note that in place of Export, we can also use the menu command File @ Save Selection As to save material in PDF or HTML form and many graphics forms. Also, in place of Import we can use the menu command Insert @ Picture @ From File to import graphics. The page guideêListingOfAllFormats in Documentation Center lists all exporting and importing formats.

Chapter 4 • Files

101

‡ Exporting and Importing Data Export["file", data, "format"] Write data into file in format data = Import["file", "format"] Read file into data in format FilePrint["file"] (Ÿ6) Look at file FileFormat["file"] (Ÿ6) Try to determine the format of file $ExportFormats Show all available export formats $ImportFormats Show all available import formats

Examples of formats: List A column. Exporting: put each item of a 1D list in its own line. Importing: form a 1D list. Table A table with space| or tab|separated values; default file extension .dat. Exporting: put each sublist of a 2D list in its own line, separating items in a line with tabs. Importing: form a 2D list. CSV A table with comma|separated values; default file extension .csv. Works similarly as Table. Text A text file; default file extension .txt. Exporting: put the whole text into the file, using several lines if the text contains newline characters \n. Importing: form a single string from the text. Lines Importing: form a string from each line of a text file to form a 1D list of strings. Words Importing: form a string from each word of a text file to form a 1D list of strings. Note that the Table, CSV, and Text formats can also be indicated by the extensions .dat, .csv, and .txt of the file. For example, instead of Export["file", data, "Table"], we can write Export["file.dat", data]; instead of Import["file.dat", "Table"], we can simply write Import["file.dat"]. Export and Import accept various options; see Documentation Center for more details.

For easy reference, here are the two most important commands to use to read data files: data = Import["file", "List"] Read a 1D table of file into data data = Import["file", "Table"] Read a 2D table of file into data

Note that by default, Export writes the file into the current working directory; the command to view this directory is Directory[]. Also by default, Import searches for a file only from certain directories; these directories can be seen by asking the value of $Path. If you want to write a file into or read a file from a nondefault directory, you have to specify the full name of the file or modify the default directories (see Section 4.2.3, p. 107). Next, we consider some special cases in more detail. ‡ A Column Export["file", data, "List"] Write 1D list data into a column file file data = Import["file", "List"] Read a column file, forming a 1D list data

Consider the following example:

data1 = 823, 41.7, 39.5, 143, 8.4 μ 10 ^ -7<;

Write the list into a file columndata.dat, putting each item in its own row: [email protected]"columndata.dat", data1, "List"D columndata.dat

102

Mathematica Navigator

Look at the file: [email protected]"columndata.dat"D 23 41.7 39.5 143 8.4e-7

Note that small and large numbers are written in a C- or Fortran-like e-form. Suppose then that we have data in columndata.dat . The file in this example is written by Mathematica, but it could be done with a text editor by saving the file in a plain text format. Now we read the file, forming a 1D list: data1a = [email protected]"columndata.dat", "List"D 923, 41.7, 39.5, 143, 8.4 μ 10-7 =

‡ A Table

For 2D lists, we need not declare the type of the data if we use the extension .dat: Export["file.dat", data] Write 2D list data into a tab|separated file file.dat data = Import["file.dat"] Read a tab| or space|separated file, forming a 2D list data

If we do not use the standard extension, we have to declare the type as Table: • Export["file", data, "Table"] Write 2D list data into a tab|separated file file • data = Import["file", "Table"] Read a tab| or space|separated file, forming a 2D list data Consider the following data:

data2 = 8823, 41.7, 39.5<, 8143, 8, 56<, 828.8, 74, 13<<;

Export it in a table form: [email protected]"tabledata.dat", data2D;

Look at the resulting file: [email protected]"tabledata.dat"D 23 143 28.8

41.7 8 74

39.5 56 13

Next, we read the file, forming sublists from the rows: data2a = [email protected]"tabledata.dat"D

8823, 41.7, 39.5<, 8143, 8, 56<, 828.8, 74, 13<<

‡ A Table with Textual Items

Define the following data:

data3 = 88"Results from an experiment"<, 8"Individual", "Measurement"<, 8"a", 23<, 8"b", 41.7<, 8"c", 39.5<, 8"d", 143<, 8"e", 8<<;

Write it into a file: [email protected]"alphanumericdata.dat", data3D;

When looking at the file, we see that the quotation marks have been dropped:

Chapter 4 • Files

103

[email protected]"alphanumericdata.dat"D Results from an experiment Individual Measurement a 23 b 41.7 c 39.5 d 143 e 8

Then read the file: data3a = [email protected]"alphanumericdata.dat"D

88Results, from, an, experiment<, 8Individual, Measurement<, 8a, 23<, 8b, 41.7<, 8c, 39.5<, 8d, 143<, 8e, 8<<

All textual items were converted into strings, as we can see by asking the InputForm: % êê InputForm

{{"Results", "from", "an", "experiment"}, {"Individual", "Measurement"}, {"a", 23}, {"b", 41.7}, {"c", 39.5}, {"d", 143}, {"e", 8}}

We can drop the first two rows: data3b = [email protected], 2D

88a, 23<, 8b, 41.7<, 8c, 39.5<, 8d, 143<, 8e, 8<<

If we begin to analyze the measurements, we can assign them to a variable meas: 8ind, meas< = data3b¨ 88a, b, c, d, e<, 823, 41.7, 39.5, 143, 8<<

In general, a textual item can be a string such as "Donkey", which has the quotation marks, or a word such as Donkey, which does not have quotation marks. When exporting a string, the text is written without quotation marks, but when exporting a textual item that is not a string, its value (if any) is written. When importing a textual item such as Donkey, the item is converted to a string ("Donkey"). ‡ Text Export["file.txt", data] Write a single string data into a text file file.txt; the file will contain

several lines if data contains newline characters \n Export["file.txt", data] Write a list of strings data into a text file file.txt; each string will be

in its own line data = Import["file.txt"] Read a text file; the whole file will be a single string; the string will

contain newline characters \n, if the file contains several lines data = Import["file.txt", "Lines"] Read a text file; each line of the file will be a string; the result

is a 1D list of strings data = Import["file.txt", "Words"] Read a text file; each word of the file will be a string; the

result is a 1D list of strings As shown previously, for text data, we need not declare the type of the data if we use the extension .txt. If we do not use this standard extension, we have to declare the type as Text~that is,

• instead of Export["file.txt", data] write Export["file", data, "Text"]; • instead of Import["file.txt"] write Import["file", "Text"]. As an example, consider the following text:

104

Mathematica Navigator

data5 = "A mnemonic for the digits of pi = 3.1415926535:\nMay I have a large container of coffee - sugar and cream?" A mnemonic for the digits of pi = 3.1415926535: May I have a large container of coffee - sugar and cream?

Here, \n is a newline character, which inserts a line break. Write the text into a text file (in Text form): [email protected]"textdata.txt", data5D;

In the file, each \n has generated a new line: [email protected]"textdata.txt"D A mnemonic for the digits of pi = 3.1415926535: May I have a large container of coffee - sugar and cream?

If we read the file in Text form, we get a single string with newline characters \n: data4a = [email protected]"textdata.txt"D A mnemonic for the digits of pi = 3.1415926535: May I have a large container of coffee - sugar and cream?

% êê InputForm

"A mnemonic for the digits of pi = 3.1415926535:\nMay \ I have a large container of coffee - sugar and cream?"

As we can see from the InputForm, the whole file became a single string. Using the Lines format gives a list of two strings, one for each line: data4b = [email protected]"textdata.txt", "Lines"D

8A mnemonic for the digits of pi = 3.1415926535:, May I have a large container of coffee - sugar and cream?<

% êê InputForm

{"A mnemonic for the digits of pi = 3.1415926535:", "May \ I have a large container of coffee - sugar and cream?"}

With Words, each word is transformed into a string: data4c = [email protected]"textdata.txt", "Words"D

8A, mnemonic, for, the, digits, of, pi, =, 3.1415926535:, May, I, have, a, large, container, of, coffee, -, sugar, and, cream?< % êê InputForm

{"A", "mnemonic", "for", "the", "digits", "of", "pi", "=", "3.1415926535:", "May", "I", "have", "a", "large", "container", "of", "coffee", "-", "sugar", "and", "cream?"} ‡ Other Commands

For reading files, Mathematica also has ReadList, which allows, for example, detailed declaration of the types of items of the files. Files can also be read item by item with OpenRead, Read, Skip, and Close. For item-specific writing, we have OpenWrite, OpenAppend, and Write. The contents of files can be searched with FindList: FindList["file", "text"] Get a list of all lines in file containing text 8c

[email protected]"alphanumericdata.dat", "c"D 39.5<

Mathematica has tools to work with databases; DatabaseLinkêtutorialêOverview in the Documentation Center.

see

guideêDatabaseConnectivity

and

Chapter 4 • Files

105

4.2.2 Exporting and Importing Graphics Export["file", fig, "format"] Write graphics fig into file in format fig = Import["file", "format"] Read file into graphics fig in format $ExportFormats Show all available export formats $ImportFormats Show all available import formats

Examples of vector graphics formats: EPS Encapsulated PostScript format (.eps) (only exporting) PDF Adobe PDF format (.pdf) WMF, EMF Windows metafile/enhanced metafile formats (.wmf, .emf) (only exporting) Examples of raster image formats: GIF GIF format (.gif) JPEG JPEG format (.jpeg, .jpg) TIFF TIFF format (.tiff, .tif) BMP Microsoft bitmap format (.bmp) WMF, EMF Windows metafile/enhanced metafile formats (.wmf, .emf) (only exporting) PICT Macintosh PICT format (.pict) (only exporting)

Options of Export include: ImageSize Absolute size of the image in printer’s points (1/72 inch) ImageResolution Resolution of the image in dpi (dots per inch) ImageRotated Whether to rotate the image to get an image in the landscape form In place of Export, we can also use the menu command File @ Save Selection As to save graphics in many different formats. This menu command supports, for example, the following formats: EPS, PDF, GIF, JPEG, TIFF, and BMP. Also, in place of Import, we can use the menu command Insert @ Picture @ From File to import graphics. Most formats can be indicated by the extensions of the file names; the extensions are given in parentheses above. For example, instead of Export["file", fig, "EPS"], we can write Export["file.eps", fig]; instead of Import["file.gif", "GIF"], we can simply write Import["file.gif"]. When exporting, the vector graphics formats are independent of the setting for ImageResolution, whereas the raster image formats depend on the value of this option. When exporting or importing, Rasterize (Ÿ6) can be used to get the file in raster format. Export and Import accept various options; see Documentation Center for more details.

Note that by default, Export writes the file into the current working directory; the command to view this directory is Directory[]. Also by default, Import searches for a file only from certain directories; these directories can be seen by asking the value of $Path. If you want to write a file into or read a file from a nondefault directory, you have to specify the full name of the file or modify the default directories (see Section 4.2.3, p. 107).

106

Mathematica Navigator

‡ Example

We first make a plot:

fig = [email protected]@xD, 8x, 0, 2 p
-0.5

1

2

3

4

5

6

-1.0

Then we export it into an EPS file: [email protected]"fig.eps", fig, ImageSize Ø 100D fig.eps

This file can then be used, for example, in MS|Word. As an example of importing, we show one of the example figures of Mathematica: [email protected]"ExampleDataêconeflower.jpg", ImageSize Ø 90D

‡ Exporting Graphics into Microsoft Word

If you are preparing a mathematical document with Microsoft Word, you may want to produce some plots with Mathematica and insert them into your Word document. First, make the plot: fig = [email protected]@xD, 8x, 0, 2 p
To export the plot into Word, the best method may vary from system to system, but the following method should work on a PC or Macintosh. Adjust the size of the plot to be suitable for the Word document, click on the plot, choose File @ Save Selection As, choose the format of the file to be EPS, give the file a name ending with .eps, and save the plot in a suitable place. Then go to your Word document, place the cursor at a suitable point, choose Insert @ Picture @ From File, locate and click the file you saved from the dialog box, and click Insert. The inserted figure will only be shown in Word as a box that contains some information about the figure; however, when printed, the figure should be OK. In Word, do not adjust the size of the plot because the size of all text in the plot then also changes, which should be avoided; any changes in size should be done with Mathematica, which does not change the size of text. In exporting as EPS, we can use the "PreviewFormat" option to get the figure shown in Word: [email protected]"fig.eps", fig, "PreviewFormat" Ø "TIFF"D

Possible values of the option are None (the default), "TIFF", "Metafile" (WMF), and "Interchange" (EPSI). On some PC systems, Save Selection As may also yield a good result with the Metafile format. Export can also be tried: [email protected]"fig.wmf", fig, ImageSize Ø sD

Chapter 4 • Files

107

‡ Exporting Graphics into LaTeX

To export a plot into a LaTeX document, save the plot in EPS format, either with File @ Save Selection As or with Export["fig.eps", fig]. Save the file in the same folder where you have saved your LaTeX document. In the starting rows of the document, add \usepackage[dvips]{graphicx}. At a suitable place in the document, add \includegraphics{fig.eps}. If you want to modify the plot, write \includegraphics[key=value]{fig.eps}, where key is width, height, angle, or scale. For example, write \includegraphics[width=8cm]{fig.eps}. This kind of command adds the plot in the place you have chosen. A more recommended method is to use a figure environment, as follows: \begin{figure}[htbp] \includegraphics[width=8cm]{fig.eps} \caption{caption to be added} \label{name used to refer to the plot} \end{figure}

Now LaTeX places the plot in the best position, a caption can be added, and we can refer to the plot with \ref. The placement of the plot in the example is directed with [htbp]. This asks to place the plot at the present point (h = here), if possible, but if not possible, then at the top of the page ( t = top), then at the bottom of the page (b = bottom), and then in a separate page (p = page), in this order of preference.

4.2.3 Locating the File ‡ The Default Locations

As noted previously, using short names of files such as data1.dat with Export and Import has some restrictions. With Export, Mathematica saves the file in a default location; the location can be seen by using the command Directory[]. With Import, Mathematica only searches the file from a list of default locations; this list can be seen by using the command $Path. Directory[] The default directory where Export writes a file $Path The default list of directories from which Import searches a file

More generally, Directory[] gives the current working directory, and $Path gives the search path (i.e., the default list of directories to search in attempting to find an external file). On my Macintosh with MacOS X, the directories are as follows: êUsersêheikki [email protected]

8êApplicationsêMathematica 6.0.appêSystemFilesêLinks, á15à, êApplicationsêMathematica 6.0.appêDocumentationêEnglishêSystem< [email protected]$Path, 3D

Thus, your files are, by default, saved in your home directory such as "/Users/heikki" . By investigating the output of $Path, we observe that when your files are read, they are searched, among others, from your home directory such as "/Users/heikki" , from the current working directory represented by ".", and from a directory such as "Users/heikki/Library/Mathematica/Applications".

108

Mathematica Navigator

If it suits you that Export writes files into Directory[] and Import searches files only from $Path, then you can use short names for the files. Otherwise, we have two possibilities. Either use the full names of files or modify the values of Directory[] and $Path. First, we consider an example of using full names. ‡ Using Full Names of Files

We have a folder DataFiles in our home directory "/Users/heikki" , and now we write a data file into this folder. Because this is not the default location, we have to give more information about the saving location. Because DataFiles is a subdirectory of our home directory, it suffices to specify the subdirectory: data5 = 8846, 71<, 822, 38<<;

[email protected]"DataFilesêdata5.dat", data5D DataFilesêdata5.dat

We could also use a full name of the file: êUsersêheikkiêDataFilesêdata6.dat

[email protected]"êUsersêheikkiêDataFilesêdata6.dat", data5D

Then we read these files. Again, because DataFiles is a subdirectory of a directory ("/Users/heikki") in $Path, it suffices to specify the subdirectory: data5a = [email protected]"DataFilesêdata5.dat"D 8846, 71<, 822, 38<<

We could also use a full name of the file: data6a = [email protected]"êUsersêheikkiêDataFilesêdata6.dat"D 8846, 71<, 822, 38<<

Note that you need not write the full names by yourself; let Mathematica do it. Simply choose Insert @ File Path and then in the dialog box select the file in which you are interested. The full name of this file is now pasted at the current location of the cursor. Note also that the full names are different in form with various computer systems. ToFileName can be used to form file names from directories. ‡ Modifying the Current Working Directory Directory[] Give the current working directory SetDirectory["dir"] Set the current working directory ResetDirectory[] Reset the current working directory to its previous value FileNames[] List all files in the current working directory

The current working directory can be changed by SetDirectory: êUsersêheikkiêDataFiles

[email protected]"êUsersêheikkiêDataFiles"D

This is now the current working directory: êUsersêheikkiêDataFiles [email protected]

Export now writes files into this default directory (without having to use full names of files). Therefore,

exporting a file into DataFile is easy:

Chapter 4 • Files

109

[email protected]"data7.dat", data5D data7.dat

Because $Path contains the current working directory ".", we can also import the file with a short name: 8846, 71<, 822, 38<<

[email protected]"data7.dat"D

We can go back to the original directory by ResetDirectory[]: êUsersêheikki

[email protected]

This is now the current working directory: êUsersêheikki [email protected]

‡ Modifying the Search Path

A nondefault folder can easily be added into the search path: $Path = [email protected]$Path, "êUsersêheikkiêDataFiles"D;

Now we can easily read files from this folder: 8846, 71<, 822, 38<<

[email protected]"data7.dat"D

If you will read data from a certain folder in several sessions, you may consider adding a command $Path = Append[$Path, "…"] in the init.m file, which can be found in a Kernel folder in $UserBaseDirectory. If you modify $Path in this way, then every time you open Mathematica, the $Path variable has the appropriate value and you can easily read the data.

4.3 Saving for Other Purposes 4.3.1 Continuing Work in Later Sessions ‡ Continuing without Recalculation

As noted in Section 3.1.1, p. 52, when we open a notebook to continue calculations, we cannot directly use any results that are already in the notebook. Suppose a notebook contains the following calculation: int = [email protected] x [email protected] [email protected], xD êê Simplify

‰x [email protected] - x [email protected] + x [email protected]

Now we open this notebook and want to continue by differentiating the integral. Note that opening a notebook only shows the notebook on the screen; opening it does not execute any commands. Thus, after opening the notebook, we cannot write D[int, x] because Mathematica does not yet know the value of int. We have to tell Mathematica the value. We have at least three ways to do this: •execute anew the command defining int; •write int = at the beginning of the value of int and execute the resulting command; or •save the value of int into a file; in a new session, load the file to get the value of int. The first method is very straightforward if the execution of the command does not take much time.

110

Mathematica Navigator

The second method also is very handy and quick: We get the value of int without doing the calculation anew. Note that the output of the original command changes to an input. If you want to keep the original output untouched, take a copy of the output and write int = at the beginning of the copy: int = ‰x [email protected] - x [email protected] + x [email protected]

‰x [email protected] - x [email protected] + x [email protected]

The third method may be worth considering if you have a very large expression that is clumsy to keep and handle in the notebook but with which you want to continue calculations in later sessions. The expression may be, for example, a large symbolic expression, a complicated plot, or a large set of generated random numbers. Saving and loading an expression is considered in the following section. The three methods also work for graphics. In the second method, take a copy of a plot of interest, paste the plot after p1 =, and execute. Now you have the plot in the variable p1 and you can modify it with options by using Show. For a plot, to get its full code with primitives, directives, and options, take a copy of the plot, select the plot, and choose Cell @ Convert To @ StandardForm. Remember also the mouse manipulations of plots mentioned in Section 5.1.1, p. 120, and interactive drawing (Graphics @ Drawing Tools, Graphics @ Graphics Inspector) considered in Section 5.1.3, p. 126. ‡ Saving and Loading Expressions a >> file Save the value of a variable a into file (clearing the file if it already exists) FilePrint["file"] View file a = << file Load file and assign the content as the value of a

In place of >> and <<, we can use Put and Get; remember that we already discussed << in Section 4.1.1 as it pertains to loading packages. As an example, we save the value of int into a file: int >> intfile

We can check that everything is all right by viewing the file: [email protected]"intfile"D E^x*(Cos[x] - x*Cos[x] + x*Sin[x])

In a new session, we can then load the file: int = << intfile

‰x [email protected] - x [email protected] + x [email protected]

Now int has the desired value. Save["file", {a, b, …}] Save definitions of variables a, b, … into file << file Load file (variables a, b, … then have the saved values)

The value of a single variable can be saved with >>. With Save, we can save several values in the same file. Note that Save appends the values to the file if it already exists (remember that >> clears an existing file; >>> or PutAppend can also be used to append expressions to an existing file). Another saving command is DumpSave. It saves expressions in a binary format and may be advantageous for very large and complicated expressions. These files can be read with <<.

Chapter 4 • Files

111

Plots can also be saved and loaded. As an example, suppose we have a plot p1. We can save it with p1 >> plot1file. Later, we can load the plot with p1 = << plot1file. Now we can add options: Show[p1, Frame Ø True].

4.3.2 Exporting to TeX, C, Fortran, and HTML ‡ Exporting to TeX

File @ Save As: Format: LaTeX Document Save the present notebook as an AMS-LaTeX file Export["file.tex", expr] Export an expression as an AMS-LaTeX file TeXForm[expr] Show the AMS-LaTeX form of an expression For exporting graphics into LaTeX, see Section 4.2.2, p. 107. Here is an example of TeXForm: i = [email protected] ^ 2 ê Hx ^ 2 + 2 x + bL, xD a2 ArcTanB

1+x

F

-1+b

-1 + b [email protected] \frac{a^2 \tan ^{-1}\left(\frac{x+1}{\sqrt{b-1}}\right)}{\sqrt{b-1}} ‡ Exporting to C and Fortran CForm[expr] Show the C form of the expression FortranForm[expr] Show the Fortran form of the expression

These commands help when you want to export Mathematica results into a C or Fortran program. For example, [email protected] (Power(a,2)*ArcTan((1 + x)/Sqrt(-1 + b)))/Sqrt(-1 + b) [email protected] (a**2*ArcTan((1 + x)/Sqrt(-1 + b)))/Sqrt(-1 + b)

If you write TeX, C, or Fortran code, you may also be interested in Splice. Suppose your C program needs the derivative of a function. In the C code, write <*D[…,…]*>, including a Mathematica command between <* and *>. Give the file a name ending with .mc. Then execute a Splice command, and you get a file in which the C code is as it was input, and the Mathematica command has been executed and written in a C form. ‡ Exporting to HTML

File @ Save As: Format: Web Page Save the present notebook as an HTML file File @ Save Selection As: Format: HTML Save the selection as an HTML file Export["file.html", expr] Export an expression as an HTML file MathMLForm[expr] Show the MathML form of the expression

112

Mathematica Navigator

4.4 Managing Time and Memory 4.4.1 Managing Time Consumption ‡ Information about Time

We have various commands that relate to time: Timing[expr] Evaluate expr; give the CPU time in seconds the kernel has used, together with the

result obtained AbsoluteTiming[expr] Evaluate expr; give the absolute elapsed time, together with the result

obtained TimeConstrained[expr, t] Stop evaluating expr after t seconds TimeUsed[] Show the used CPU time in the current session SessionTime[] Show the elapsed time in the current session DateList[] (Ÿ6) Current time: {year, month, day, hour, minute, second} DateString[] (Ÿ6) Current time: “weekday day month year hour:minute:second“ DatePlus[date, n] (Ÿ6) The date n days after date DateDifference[date1, date2] (Ÿ6) The number of days from date1 to date2

The time is measured in steps of $TimeUnit, which, in many systems, has the default value of 1/100 second. Note that doing the same calculation again or doing a similar calculation may take much less time because Mathematica may have already loaded some files or stored results. The following is an example of Timing: [email protected] ^ 137 - 1D êê Timing

86.47204, 8832 032 215 596 496 435 569, 1<, 85 439 042 183 600 204 290 159, 1<<<

If we only want to see the time~not the result~we can use the semicolon. In place of the result, we then have Null: Hran = [email protected]@D, 810 ^ 6
The execution time can be seen in the lower left-hand corner of the window by choosing Format @ Option Inspector…, setting Scope to be Selected Notebook, going to Notebook Options @ Evaluation Options, and then selecting ShowTiming as the value of EvaluationCompletionAction. This time is somewhat longer than the time given by Timing because it includes the time to format and show the result. ‡ Time-Saving Tips

•It is good to have plenty of random access memory (RAM). To some extent, the more memory Mathematica has available, the speedier it is. Also, remember that virtual memory on the hard disk is much slower than actual physical RAM. •If you work with a heavy and time-consuming problem in several sessions, you perhaps need not start from scratch each time. Instead, try to continue the work from where you left off (see Section 4.3.1, p. 109).

Chapter 4 • Files

113

•Avoid using so-called “arbitrary-precision” numbers. Calculations with these numbers are done by software in Mathematica and are much slower than calculations done with the hardware-implemented, machine-precision numbers. This point is explained in more detail in Sections 12.2.2, p. 404, and 12.3.1, p. 409. The precision used in calculations can often be set with the WorkingPrecision option. Resist changing the default value MachinePrecision of this option. Of course, if the problem is ill-conditioned and round-off errors have an effect, the option mentioned should be used by giving it a large enough value, such as 20. In this way, the problem may be solved without difficulties. •In numerical routines such as NIntegrate, FindRoot, FindMinimum, and NDSolve, the default precision may sometimes be more than you actually need (e.g., if the result is used in plotting). Lowering the precision requirements PrecisionGoal and AccuracyGoal reduces the calculation time (for these options, see Section 12.3.1, p. 409). •When plotting largely varying functions, you can sometimes get better results if you increase the value of the PlotPoints option. However, after a certain value you cannot see any difference in the plot, and you merely waste time because the larger the value of PlotPoints, the longer it takes to produce the plot. •The execution time of a program may significantly depend on the design of the program; see Wagner (1996) for detailed experiments and recommendations. Some points are as follows. Use built-in commands if possible. If the result of the program consists of decimal numbers, use decimal numbers as early as possible (i.e., avoid calculating with exact numbers). Use the functional programming style (see Section 18.3, p. 568). Avoid using Append, AppendTo, Prepend, and PrependTo. Compile your functions (see Section 17.2.3, p. 528). •While awaiting the result of a time-consuming command, you can edit the notebook by adding, for example, text to explain what you have done and what the results mean. You can also write new commands so that they are ready to be executed when the time-consuming command has printed its result. •You can calculate with Mathematica while waiting for the result of a time-consuming command. This can be done by using a subsession. Once you have entered a subsession, the execution of the timeconsuming command is interrupted, and you can do some shorter calculations during the subsession. After you exit the subsession, the execution of the time-consuming command continues. To enter a subsession, choose Evaluation @ Interrupt Evaluation. A dialog appears where you can ask to get a subsession; wait for the cell bracket to change to a special bracket. Now you can do some shorter calculations. To exit the subsession and continue the long calculation, execute Return[]. •A good way to save time may be to use a remote kernel. If your machine is not powerful enough, you can save time by using the greater power of a remote machine. If your machine is powerful enough, you can still consider using a remote kernel or even several remote kernels to do parts of your calculations. In this way, you can do several calculations at the same time. To define a remote kernel, choose Evaluation @ Kernel Configuration Options.

4.4.2 Managing Memory Consumption ‡ Information about Memory

In the following box, we list commands that relate to the consumption of memory. The kernel needs memory to store both the code of Mathematica and the results of computations. The latter material is called “data.”

114

Mathematica Navigator

ByteCount[expr] Bytes used by expr if sharing (see Memory-Saving Tips) is not used MemoryConstrained[expr, b] Stop evaluating expr if more than b bytes are needed for the

evaluation MemoryInUse[] Memory in bytes currently being used to store data in the kernel MemoryInUse[$FrontEnd] (Ÿ6) Memory in bytes currently being used in the front end MaxMemoryUsed[] Maximum memory in bytes used to store data thus far

Note that the kernel of Mathematica keeps in RAM all the results of the current session, and this means that the memory consumption of the kernel steadily grows as your session continues. However, Mathematica uses kernel memory sparingly and deletes all intermediate results that are no longer needed. It may be wise to divide long sessions into shorter ones by occasionally quitting Mathematica and starting a new session with a clean sheet, maximum memory, and maximum speed. In notebook environments, we can also quit the kernel only by choosing Evaluation @ Quit Kernel. ‡ Memory-Saving Tips

•Ending a command with the semicolon (;) prevents the result from being displayed. This saves memory, especially for large expressions. It also saves your screen area by not cluttering it with uninteresting formulas or graphics and thus helps you to manage the flow of computation. •You can delete all output cells by choosing Cell @ Delete All Output. This releases front-end memory and makes the notebook smaller. The memory saving may be very substantial if the notebook contains many plots. You can recalculate the commands later if needed. •When you have finished a plot and no longer want to change or print it, you can greatly save frontend memory and the size of the notebook by converting the plot to bitmap form. Select the plot with the mouse and choose Cell @ Convert To @ Bitmap. The plot does not change in any way on the screen, but the PostScript code behind the plot is discarded. •Use Compress to compress large expressions. They can be uncompressed with Uncompress. • Execute Share[] to reduce the amount of kernel memory. This command shares the storage of common subexpressions between different parts of an expression or between different expressions. The output of the command is the memory saved. •One method of saving memory is to run only the front end on your machine and to run the kernel in another machine. Then only the front end takes memory from your machine, and you can take advantage of the possibly larger RAM and speedier processor of the remote kernel. To define a remote kernel, choose Evaluation @ Kernel Configuration Options.

5 Graphics for Functions Introduction 115 5.1 Basic Plots for 2D Functions 116 5.1.1 Plotting One Curve 116 Plot, AspectRatio, PlotRange, Ticks, Play 5.1.2 Plotting Several Curves 121 Plot, Show, Tooltip, GraphicsRow, GraphicsGrid, etc. 5.1.3 Interactive Drawing 126 5.2 Other Plots for 2D Functions 132 5.2.1 Parametric Plots 132 ParametricPlot, PolarPlot 5.2.2 Logarithmic Plots 133 LogPlot, LogLinearPlot, LogLogPlot 5.2.3 Implicit Plots 134 ContourPlot 5.2.4 Filled Plots 135 Filling, FillingStyle 5.2.5 Region Plots 136 RegionPlot, ParametricPlot 5.2.6 Complex Plots 137 Re, Im, Abs, RegionPlot, ContourPlot, ParametricPlot 5.3 Plots for 3D Functions 139 5.3.1 Basic Plots 139 Plot3D, ContourPlot, DensityPlot 5.3.2 Special Plots 142 ParametricPlot3D, RegionPlot3D, GradientFieldPlot, etc. 5.3.3 Stereograms 145 SIS 5.4 Plots for 4D Functions 147 5.4.1 Simple Methods 147 VectorFieldPlot3D, GradientFieldPlot3D 5.4.2 Surfaces of Constant Value 149 ContourPlot3D

Introduction Straight line~the shortest way between two points.~Euclid Cycloid~the fastest way between two points.~Johann Bernoulli Curve~the loveliest way between two points.~Mae West The plotting capabilities of Mathematica are impressive. There are many ready-to-use commands such as Plot, Plot3D, ParametricPlot, ParametricPlot3D, ListPlot, ListPlot3D, and ContourPlot, which often give good results. In case we want to modify the plots, we have many options at our disposal that may help us to obtain just the result we want. If there is not a suitable plotting command, we can build the plot from so-called graphics primitives, or we can write a program. This chapter explains graphics for functions. Graphics primitives and directives are addressed in Chapter 6 and options for graphics in Chapter 7. In Chapter 8, we consider graphics for data, and in Chapter 9, we discuss built-in data of Mathematica. Exporting and importing figures is explained in Section 4.2.2, p. 105.

116

Mathematica Navigator

Mathematica 6 contains an impressive new feature called dynamics. It enables us to create dynamic interfaces where we can adjust some parameters and look at how the result changes. This is very useful especially in studying how a plot depends on some parameters. A special case of dynamic interfaces is also animating. We consider dynamic interfaces and animations in Chapters 10 and 11. Graphics is one of the central parts of Mathematica and contains a wealth of material. You may first want to read only the topics you are interested in now and go on to other topics later. More about Mathematica graphics can be found in Smith & Blachman (1995), Wickham-Jones (1994), and Trott (2004a). The graphics functionality has significantly changed and been enhanced in Mathematica 6. If you would like to use version 5 graphics instead, execute <
5.1 Basic Plots for 2D Functions 5.1.1 Plotting One Curve ‡ The Basic Plotting Command Plot[f, {x, a, b}] Plot f when x takes on values from a to b

The f can be an explicit expression, the name of an expression, or the name of a function (for functions, see Section 2.2.3, p. 39). Therefore, to plot the density function of the standard normal distribution, we can write the following:

[email protected]@-x ^ 2 ê 2D ê [email protected] pD, 8x, -4, 4
or

or

f = [email protected] ^ 2 ê 2D ê [email protected] pD [email protected], 8x, -4, 4
The second method is often handy because from the output of f = … we can first check that the expression is correct and because the plotting command then becomes simpler and shorter. We try the second method: f = [email protected] ^ 2 ê 2D ê [email protected] pD -



x2 2

2p p1 = [email protected], 8x, -4, 4
-2

2

4

Chapter 5 • Graphics for Functions

117

Plot works by first sampling the function to be plotted at 51 (almost) equally spaced points. If the function changes rapidly somewhere in the interval, then more points are automatically sampled in such regions. Plot is in this sense adaptive. The sampled points are then joined by straight lines. For

more about the algorithm behind Plot, see Section 7.4.6, p. 207. ‡ Other Examples

The expression to be plotted can consist of several definitions: mu = 1; sigma = 0.7; c = 1 ê Hsigma [email protected] pDL; g = [email protected] HHx - muL ê sigmaL ^ 2D; p2 = [email protected] g, 8x, -4, 4
-2

2

4

Next we try a function:

[email protected]_, mu_, sigma_D := 1 ê Hsigma [email protected] pDL [email protected] ê 2 HHx - muL ê sigmaL ^ 2D p3 = [email protected]@x, 0, 1.5D, 8x, -4.1, 4.1
-2

2

4

We can plot almost any kind of expression. Next we plot a function defined with an integral: [email protected]@[email protected] ^ 2D, 8t, 0, x
1.0

1.5

2.0

‡ Discontinuous Functions Plot[f, {x, a0, a1, …, ak}] Plot f when x takes on values from a0 to ak, potentially breaking the

curve at each of the ai Plot[f, {x, a, b}, Exclusions Ø list] Plot f when x takes on values from a to b, excluding

values of x given either explicitly or implicitly (in the form of equations) in the list list Plot[f, {x, a, b}, Exclusions Ø None] Do not exclude any values of x

118

Mathematica Navigator

Here is a discontinuous function:

[email protected]@xD, 8x, 0, 2 p<, Ticks Ø 88p ê 2, 3 p ê 2<, Automatic
p

3p

2

2

-6

Strictly speaking, the vertical lines do not belong to the graph of the function. To get rid of the vertical lines, define intermediate points at the singularities. We can also use the Exclusions option to tell the points to be avoided either explicitly as a list or implicitly by an equation: [email protected]@xD, 8x, 0, p ê 2, 3 p ê 2, 2 p
:

6

6

6

4

4

4

2

2

-2

1

2

3

4

5

6

, -2

2 1

2

3

4

5

6

, -2

-4

-4

-4

-6

-6

-6

1

2

3

4

5

6

>

Next, we plot another discontinuous function. Now Mathematica automatically excludes the point of discontinuity~that is, we do not have a vertical line at the discontinuity. If you want a vertical line, use the Exclusions option with value None: [email protected]@[email protected], x < 3 p ê 4<, [email protected], x ¥ 3 p ê 4<
:

1.0

0.5

0.5 0.5

1.0

1.5

2.0

2.5

3.0

,

0.5

-0.5

-0.5

-1.0

-1.0

1.0

1.5

2.0

2.5

3.0

>

‡ Using Options

Mathematica often draws very nice plots. Occasionally, however, we may want to make someadjustments. When this is the case, many options are available. Each option has a default value that is used if another value is not given. One of the options is AspectRatio (the ratio of height to width of the plot). The default value of this option is 1/GoldenRatio = 0.618. With the default value, we get the following plot: p4 = [email protected]@xD, 8x, 0, 2 p
2

3

4

5

6

Chapter 5 • Graphics for Functions

119

If we want to plot in such a way that one unit on the x axis has the same length as one unit on the y axis, then we can give AspectRatio the value Automatic:

[email protected]@xD, 8x, 0, 2 p<, AspectRatio Ø AutomaticD 1.0 0.5 -0.5 -1.0

1

2

3

4

5

6

We could also use Show and define the option there: [email protected], AspectRatio Ø AutomaticD 1.0 0.5 -0.5 -1.0

1

2

3

4

5

6

The standard way when plotting is to first use the default values for the options (i.e., writing no options in the plotting command). If the result is not satisfactory, change the value of some of the options. To make changes, we have two approaches. First, we can write the options into the original plotting command and then execute the command anew. Second, we can write the options into a Show command. Note that Show does not redo the computations; only the way the figure is shown is changed. This means that computer time is saved, at least for complex figures. ‡ Important Options

We consider in detail all the options of Plot in Chapter 7. However, here are some of the most important options. For each option, we mention several examples of values. Throughout this book, we use the convention that the default value of each option is always mentioned first. AspectRatio Ratio of height to width of the plot; examples of values: 1/GoldenRatio (= 0.618), Automatic (one unit on both axes has the same length), 0.4 PlotRange Range of coordinates in the plot; examples of values: {Full, Automatic}, All, {-1, 1} Ticks Ticks on the axes; examples of values: Automatic, {{ p, 2 p, 3 p}, Automatic}, {{1, 2, 3}, {-2, -1, 1, 2}}

Sometimes Plot cuts off low or high parts of the function in order to plot the remaining parts more accurately. If you want to see the whole function in the given interval, give PlotRange the value All. If the ticks of a plot do not satisfy you, define them with Ticks. You can specify the ticks on the x or y axis and let Plot choose the ticks on the other axis, or you can specify the ticks on both axes. Options can be written in any order, but they must be the last entries in the command~that is, they must be written after the expression and the plotting interval. For example, [email protected]@xD, 8x, 0, 2 p<, AspectRatio Ø Automatic, PlotLabel Ø [email protected], Ticks Ø 88p, 2 p<, 8-1, 1<
1 p -1

2p

120

Mathematica Navigator

‡ Mouse Manipulations

In notebook environments, we can change a plot in several ways using the mouse. First, click on the plot with the mouse; a selection rectangle appears. •To resize the plot, drag with the mouse by any of the handles of the selection rectangle. When dragging, the width and height of the plot can be read from the bottom left-hand corner of the window (the size is expressed in printer’s points; one printer’s point is 1/72 of an inch). Note that the size of all text remains unchanged when resizing the plot. Also, the form of the plot remains the same. To change the form of the plot, hold down the ˜ key and then drag (or use the AspectRatio option). Changing the default size of figures is considered soon. •To move the plot on the screen (and thus adjust the margins around the plot), drag with the mouse by one of the edges of the selection rectangle (but not by any of its handles). The plot moves and a second selection rectangle appears outside the original seclection rectangle. The outer selection rectangle changes its size as you move the plot. The size of the outer selection rectangle can be changed by dragging by one of its handles. While dragging, the width and height of the outer selection rectangle can be read from the bottom left-hand corner of the window. By moving the plot on the screen, we can set the margins around the plot. To get equal margins on the top and bottom and on the left and right of the figure, shift-drag by one of the handles of the outer selection rectangle. To get rid of the margins, shift-drag by one of the handles of the outer section rectangle to the top left corner. •To crop the plot, hold down the ‚ key in Windows or the Ì key on Macintosh, and drag by one of the handles of the (inner) selection rectangle. The size of the plot can be read from the bottom left-hand corner of the window. By cropping, you can either make more room around the plot or cut off some parts of the plot (croppings are not permanent). •To go back to the standard size and position, click on the plot and choose Graphics @ Rendering @ Make Standard Size (this does not affect a possible cropping). •To align several plots according to the first plot, select the plots by dragging over the cell brackets so that all plots to be aligned become selected (do not worry if some nongraphics cells also become selected), and then choose Graphics @ Rendering @ Align Selected Graphics. Plots can be aligned with respect to any side of the first plot. Plots can also be made the same size as the first plot. •To make a copied graphic evaluatable, select the graphic and choose Cell @ ConvertTo @ StandardForm. To change the default size of all future plots in the current notebook or in all current and future notebooks, choose Format @ Option Inspector, select Scope to be Selected Notebook (if you want to change the size in the current notebook only) or Global Preferences (if you want to change the size in all notebooks), go to Graphics Options @ Image Bounding Box, and change the width and height values for ImageSize. The default value is 350 printer’s points. Divide the value by 72 to get the width of figures in inches. For example, with the default value, the width of the figure is approximately 4.86 inches. Once you have typed a new value, remember to press Á. Note that the sizes of old plots do not change according to the new standard size unless you replot them. Another way to change the default size of all future plots in the current session is to use SetOptions, as in the following example: [email protected], ImageSize Ø 150, BaseStyle Ø 8FontSize Ø 7
Here, we also changed the size of the font in plots.

Chapter 5 • Graphics for Functions

121

‡ Sound

With the Play command, we can hear sound. For example, the following command plays a pure tone with a frequency of 400 hertz for 2 seconds: [email protected]@2 p 400 tD, 8t, 0, 2
Note that we also have the Audio` and Music` packages.

5.1.2 Plotting Several Curves ‡ Suppressing the Display of a Plot

Before discussing plots of several curves, we recall from Section 2.1.1 the use of the semicolon ( ;) to suppress the display of a plot: Plot[f, {x, a, b}]; Plot f but do not show the plot

Often when we prepare a plot, we, naturally, would like to see the plot. However, when preparing several plots that will later be combined with commands such as Show or GraphicsGrid, we may want to suppress the display of the separate plots to make the presentation clearer and shorter both on the screen and on the paper. Suppressing the display is easy: Simply end the command with the semicolon ; (in earlier versions of Mathematica we had to use the DisplayFunction option). ‡ Showing Several Curves in the Same Plot Plot[{f1, f2, … }, {x, a, b}] Plot several expressions in the same figure Show[p1, p2, … ] Combine several plots in the same figure

To get several curves in the same plot, we have two methods. First, we can plot the curves in one command, giving the expressions as a list: [email protected]@xD, [email protected]<, 8x, -p, p
-3

-2

-1

1

2

3

-0.5 -1.0

Note that the curves automatically have different colors. We can also plot each curve separately and then combine the plots with Show: p1 = [email protected]@xD, 8x, -p, p
122

Mathematica Navigator

[email protected], p2D 1.0 0.5

-3

-2

-1

1

2

3

-0.5 -1.0

Now the curves have the same color. We can also write complete plotting commands inside Show: [email protected]@[email protected], 8x, -p, p
-3

-2

-1

1

2

3

-0.5 -1.0

Here is another example. It illustrates the use of a precomputed list of expressions and the use of Table inside Plot:

t = [email protected], [email protected] xD, [email protected] xD<;

[email protected]@xD, [email protected] xD, [email protected] xD<, 8x, 0, Pi
:

1.0

1.0

0.5

0.5 0.5

1.0

1.5

2.0

2.5

3.0

,

1.0 0.5 0.5

1.0

1.5

2.0

2.5

3.0

,

0.5

-0.5

-0.5

-0.5

-1.0

-1.0

-1.0

1.0

1.5

2.0

2.5

3.0

>

We can see that, with the exception of the last plot, the curves are given different colors. In the last plot, we get different colors if we add //Evaluate after the Table command. ‡ Tooltips Tooltip[f] (Ÿ6) Show expression f as a tooltip when the mouse pointer is moved over the area

where f is plotted Tooltip[f, label] Show label label as a tooltip

With Tooltip we can see the expression plotted or another label when moving the mouse pointer over the plot:

Chapter 5 • Graphics for Functions

123

[email protected]@[email protected]@n xDD, 8n, 3
"D

1.0 0.8 0.6 0.4 0.2 0.0 0.5 1.0 1.5 2.0 2.5 3.0

1.0

1.0

1.0

0.5

0.5

0.5

-0.5 -1.0

0.5 1.0 1.5 2.0 2.5 3.0

-0.5 -1.0

0.5 1.0 1.5 2.0 2.5 3.0

-0.5

0.5 1.0 1.5 2.0 2.5 3.0

-1.0

This is a row of four separate plots (Row, Column, and Grid are considered in Chapter 17). We also have GraphicsRow, GraphicsColumn, and GraphicsGrid. With these commands, we get as a result a single graphic:

124

Mathematica Navigator

[email protected] 1.0 0.8 0.6 0.4 0.2

1.0

1.0

0.5

0.5

-0.5

0.0 0.5 1.0 1.5 2.0 2.5 3.0

0.5 1.0 1.5 2.0 2.5 3.0

-1.0

-0.5

1.0 0.5 0.5 1.0 1.5 2.0 2.5 3.0

-1.0

-0.5

0.5 1.0 1.5 2.0 2.5 3.0

-1.0

Here are the special commands to arrange plots. GraphicsRow[{p1, p2, … }] (Ÿ6) Show plots side by side GraphicsColumn[{p1, p2, … }] (Ÿ6) Show plots one below the other GraphicsGrid[{{p11, p12, … }, {p21, p22, … }, … }] (Ÿ6) Show plots as a 2D grid [email protected]@t, 2DD 1.0 0.8 0.6 0.4 0.2

1.0 0.5

-0.5

0.0 0.5 1.0 1.5 2.0 2.5 3.0

-1.0

1.0

1.0

0.5

0.5

-0.5

0.5 1.0 1.5 2.0 2.5 3.0

-1.0

0.5 1.0 1.5 2.0 2.5 3.0

-0.5

0.5 1.0 1.5 2.0 2.5 3.0

-1.0

‡ Options GraphicsRow, GraphicsColumn, and GraphicsGrid have many options; execute, for example, Options[GraphicsGrid] to get a list of all of them. Here are some of the options.

Some options of GraphicsRow, GraphicsColumn, and GraphicsGrid: Spacings Horizontal and vertical space between plots; examples of values: Scaled[0.1], {Scaled[0.2], Scaled[0.1]} ImageSize Size of the whole grid; examples of values: Automatic, 300 ImageMargins Margins around the whole grid; examples of values: 0., 5 AspectRatio Ratio of height to width for the whole grid; examples of values: Automatic, 0.5 Background Background color; examples of values: None, LightGray Frame Where to draw frames; examples of values: None, True (frame around the whole grid), All

(all items become boxed), {None, All} (frame around each row) FrameStyle Style of frames; examples of values: Automatic, Thick Dividers Where to draw lines; examples of values: None, All (all items become boxed), Center (all

interior dividers), {None, All} (no column lines, all row lines) Many of the options have more advanced forms of values; see Section 15.2, p. 470, in which we consider the options of Grid. To give an example of GraphicsGrid, prepare four plots:

Chapter 5 • Graphics for Functions p1 = [email protected]@xD, p2 = [email protected]@xD, p3 = [email protected]@xD, p4 = [email protected]@xD,

8x, 8x, 8x, 8x,

0, 0, 0, 0,

2 p<, 2 p<, 2 p<, 2 p<,

125

PlotLabel Ø [email protected]; PlotLabel Ø [email protected]; PlotLabel Ø [email protected], PlotRange Ø 8-11, 11
With the PlotLabel option we get the label above the grid:

[email protected], p2<, 8p3, p4<<, Spacings Ø [email protected], Frame Ø All, FrameStyle Ø Blue, Background Ø LightYellow, ImageSize Ø 260, PlotLabel Ø [email protected]"Trigonometric functions", 10, Bold, FontFamily Ø "Times"DD

Trigonometric functions

sinHx L 1.0

1.0

0.5

0.5

-0.5

1

2

-1.0

3

4

5

6

-0.5

tanHx L

10

5

5 1

2

3

2

-1.0

10

-5

1

cosHx L

4

5

6

-10

-5

3

4

5

6

5

6

cotHx L

1

2

3

4

-10

With the Labeled command we get the label below the grid:

[email protected]@88p1, p2<, 8p3, p4<<, Spacings Ø [email protected], Frame Ø All, FrameStyle Ø Blue, Background Ø LightYellow, ImageSize Ø 260D, [email protected]"Trigonometric functions", 10, Bold, FontFamily Ø "Times"DD sinHx L

cosHx L

1.0

1.0

0.5

0.5

-0.5

1

2

-1.0

3

4

5

6

-0.5

10

5

5

-5

1

2

3

4

2

-1.0

tanHx L

10

-10

1

5

6

-5

3

4

5

6

5

6

cotHx L

1

2

3

4

-10

Trigonometric functions ‡ How Show Handles Conflicting Settings

When Show is used to combine plots, Mathematica has to decide what to do if the plots have conflicting settings. Indeed, the plotting intervals may be different, and the values of some options may be different. Mathematica uses the following rules: •use the plotting interval of the first plot; •use the values of the options of the first plot; and •options given in Show override those of the first plot.

126

Mathematica Navigator

The second rule, as inevitable it is for Mathematica, may cause trouble for us. It means that all option settings other than those in the first plot are simply discarded! We have perhaps carefully set various options in all plots, but when the plots are combined, only the options from the first plot are used. To correct the situation, in Show, we can give some of the options we have used in the plots. If you know in advance that you do not need the separate plots as such but will combine the plots into one figure, then fine-tune only the combined plot by giving suitable options in Show; do not fine-tune each plot. As an example, consider the following plots: p1 = [email protected]@xD, p2 = [email protected]@xD, p3 = [email protected]@xD, p4 = [email protected]@xD, p5 = [email protected]@xD,

8x, 8x, 8x, 8x, 8x,

-p, p
Try to combine some plots:

[email protected], p2D, [email protected], p4D< 1.0

1.0

:

0.8

0.5

>

0.6 -3

-2

,

-1

1

2

3

-0.5

0.4 0.2

-1.0

0

1

2

3

4

5

6

Plots p1 and p2 have different plotting intervals, so the combined plot uses the interval of the first plot. Plots p3 and p4 have conflicting plot ranges, so the plot range of the first plot is used. [email protected], p5D, [email protected], p5, PlotRange Ø 80, 1<, Ticks Ø 88-p, p<, 81<
1.0

:

0.5

-3

-2

-1

>

, 1

2

3

-0.5 -1.0

-p

p

Plots p1 and p5 have conflicting ticks (the first plot uses the default ticks), so the ticks of the first plot are used. The last plot shows that we can adjust the options in Show.

5.1.3 Interactive Drawing ‡ Graphics Inspector and Drawing Tools

In Mathematica, graphics are normally generated by commands such as Plot or ListPlot. The style of a plot can be changed in many ways with options such as PlotStyle; options are considered in Chapter 7. Sometimes we want to add into a plot some elements or primitives, as they are called in Mathematica, such as points, lines, or text. This can be done with the Prolog and Epilog options (see Section 7.3.6, p. 201). Sometimes we want to build up a graphic from scratch by using graphical primitives. This can be done with the Graphics (or Graphics3D) command (see Section 6.1.1, p. 152).

Chapter 5 • Graphics for Functions

127

In addition to the use of the PlotStyle, Prolog, and Epilog options and the Graphics command, in Mathematica we can also draw interactively with the mouse. By choosing Graphics @ Graphics Inspector and Graphics @ Drawing Tools, we get the following windows:

• With the 2D Graphics Inspector window we can change the styles of components of a plot. • With the 2D Drawing window we can add primitives to a plot or build up a graphic from scratch. The 2D Graphics Inspector window can also be shown by clicking on the upper right button on the 2D Drawing window. ‡ Changing the Style of Plots

To change the style of a curve or point set, of the 2D Drawing

•double-click on the curve or one of the points with the selection tool

window; and • choose, from the 2D Graphics Inspector, the styles you want to apply for the curve. In general, • for a curve, we can change the color, thickness, and dashing; and • for a set of points, we can change the color and point size. As an example, here we have three plots:

[email protected]@xD, 8x, 0, 2 p
:

1.0

1.0

1.0

0.5

0.5

0.5

1

2

3

4

5

6

,

, 1

2

3

4

5

1

6

-0.5

-0.5

-0.5

-1.0

-1.0

-1.0

We have changed the plots as follows:

2

3

4

5

6

>

128

:

Mathematica Navigator 1.0

1.0

0.5

0.5

1

2

3

4

5

6

,

1.0 0.5 1

2

3

4

5

6

,

1

-0.5

-0.5

-0.5

-1.0

-1.0

-1.0

2

3

4

5

6

>

To get the first plot, we selected the curve by double-clicking on it. Be careful: The double-clicking has to be done on the curve, not on the white parts of the plot. Then we set, from the 2D Graphics Inspector, the color to dark red, thickness to approximately 2, and dashing to Dashed. To get the second plot, we first selected the point set by double-clicking on one of the points. We set the color to red and point size to approximately 4. To get the third plot, we first selected the curve by double-clicking on it. We set the color to dark blue, thickness to approximately 2, and point size to approximately 4. To change the color of the points, we have to select the points by double-clicking one of them. Then we set the color to dark red. With the 2D Graphics Inspector, we can also select the opacity of a color. By double-clicking the color panel on the inspector, we get a more advanced color selector (the same we get from Insert @ Color). ‡ Using the 2D Drawing Tools

The 2D drawing tools can be used in two ways: • Add some primitives to an existing plot • Draw a graphic from scratch on the 2D Drawing

To start the second method, simply click on the New Graphic button

window or choose Graphics @ New Graphic. We get an empty graphic. Then add some suitable primitives. With the 2D drawing tools, we can draw • point • line • text

; , arrow

, line segments

and traditional form text

• filled or unfilled disk/circle

, and freehand line ; and

, rectangle/square

In addition, with the coordinate-picking tool

;

, and polygon

.

we can read and copy coordinates.

‡ Selecting a Drawing Tool

On the 2D Drawing window, we can select a drawing tool in two ways: •To draw a single primitive, click one time on the corresponding tool on the 2D Drawing window. Then click or drag on the plot. •To draw several primitives of the same kind, double-click on the corresponding tool (to go back to the normal arrow mouse pointer, click on this tool on the 2D Drawing window). To select a drawing tool to draw a single primitive, we can also type a special key:

Chapter 5 • Graphics for Functions

129

• point, p • line, l; arrow, a; line segments, s; freehand line, f • text, t; traditional form text, m • disk/circle, c; rectangle, q; polygon, g • mouse pointer, o Thus, to draw, for example, an arrow, type a to get the arrow tool and then draw. ‡ Drawing Points, Lines, Arrows, and Text

Points, lines, arrows, and text can be drawn as follows, after selecting the suitable tool: • To draw a point, click on the plot at a suitable location. • To draw a line, click on the starting point, keep the mouse button down, and drag to the end point. • To draw an arrow, proceed as with a line. •To draw line segments, click on the starting point, release the mouse button, move the mouse to the next point, click with the mouse, release the mouse button, …, move the mouse to the last point, and double click. •To draw a freehand line, click on the starting point, keep the mouse button down, move the mouse as you want, and at the end point release the mouse button. The resulting curve consists of line segments with breaking points. The quality of the line depends on the speed of the mouse: The slower you move the mouse, the more line segments and breaking points the resulting curve will have. • To add a text, click on the starting point of the text and type the text. •To add a traditional form text such as a formula, click on the starting point of the formula and type the formula or build the formula with the aid of palettes. In the following plot, we have added a point, an arrow, a text, and a formula. [email protected]@xD, 8x, 0, 2 p
1.0

point of inflection

0.5

1

2

3

4

5

6

-0.5 -1.0

Note that once we have changed the style of a plot or added a primitive, the higher-level cell bracket at the right, grouping the command and the plot, disappears. This is a useful feature because if we execute the plotting command again, the modified plot remains on the notebook. ‡ Drawing Filled Primitives

Filled ellipses, rectangles, and polygons can be drawn as follows: •To draw an elliptical disk or filled ellipse, click on the center point, keep the mouse button down, and drag until the disk has a suitable size and form. •To draw a filled rectangle, click on one of the vertices, keep the mouse button down, and drag to the opposite vertex. •To draw a filled polygon, click on the starting point, release the mouse button, move the mouse to the next point, click with the mouse, release the mouse button, …, move the mouse to the last point, and double click.

130

Mathematica Navigator

‡ Coloring Filled Primitives

A filled disk, rectangle, or polygon can be colored in two ways: Either the whole primitive has the same color, or the inside and the edge of the primitive have different colors. To set the colors of filled primitives, we need the color settings on the top left part of the 2D Graphics Inspector. There, we have two squares: • The upper left square shows the color of the inside (or face) of the filled primitive. • The lower right square shows the color of the edge of the filled primitive. To change the color of the inside or edge of a filled primitive, select the primitive, set (by clicking if necessary) one of the squares in the 2D Graphics Inspector to be the topmost square, and choose a color from the panel in the inspector. Then set the other square to be the topmost square and choose a color. ‡ Drawing Unfilled Primitives

To get an unfilled primitive, we can set the primitive to have nothing as the inside and black (or another color) as the edge. Indeed, by clicking repetitively on one of the two squares on the inspector window, the corresponding color setting toggles between a color and nothing. In this way, we can draw unfilled primitives: •To get an unfilled ellipse, rectangle, or polygon, set, by clicking on the two squares on the inspector, the inside color to nothing and the edge color as black (the edge color can then be changed to another color). Then draw a disk, rectangle, or polygon. ‡ Constraining Primitives

A primitive (other than a point or a text) can be constrained as follows, by shift-dragging: • A line and arrow can be constrained to horizontal or vertical direction. • A line segment can be constrained to have horizontal or vertical segments. • A disk can be constrained to a circle form. • A rectangle can be constrained to a square. • A polygon can be constrained to have horizontal or vertical edges. In the following plot, we started from an empty graphics, drew a disk (by constraining it to the form of a circle), selected it, copied it, and pasted it two times. Two of the copies were moved to other places. Suitable colors were given to the disks, and a suitable opacity was defined.

‡ Selecting Primitives and Their Components

The primitives can be modified in various ways. In modifying, the depth at which the primitive is selected with the selection tool is essential. The depth of selection is controlled by clicking various times.

Chapter 5 • Graphics for Functions

131

• At the lowest level, the selection rectangle appears around the primitive. At this level, the primitive as a whole can be modified. We say simply that the primitive is selected. • At the next level (by continuing the clicking), the components of the primitive become visible; for example, for a line we can see the line and its end points. We say that the components of the primitive are selected. ‡ Moving and Resizing Primitives

To change a primitive as a whole, first select the primitive. Then do the following: • To move a primitive, drag either on an edge of the selection rectangle or on the primitive. • To change the size of a primitive, drag on one of the handles of the selection rectangle. To change the size in such a way that the form of the primitive remains the same, hold down the shift key and then drag on a handle. • To change the color, point size, thickness, or dashing, use the 2D Graphics Inspector. ‡ Modifying the Components of Primitives

To change the components of a primitive, first select the components of the primitive. Then do the following: • Changing a line: To move the line, drag on the line. To change the starting or ending point of the line, drag on the corresponding point. • Changing an arrow: Do as with a line. To change the form, size, or position of an arrowhead, either select the arrow or select the end point of the arrow. Then change the arrowhead from the 2D Graphics Inspector. • Changing a set of line segments: To move a line segment, drag on that segment. To move a breaking point, drag on that point. • Changing a freehand line: Drag either on a line segment or on a breaking point. • Changing a text or traditional form text: Set the cursor at a suitable location and modify or type. • Changing a disk: To change the center point, drag on it. To change the size or form of the disk, drag on the point of one of the vertices around the disk. • Changing a rectangle: To change the size or form, drag on one of the two points on opposite vertices. • Changing a polygon: Drag either on a line segment or on a breaking point. ‡ Grouping Primitives and Moving Them Front and Back

Primitives can be grouped together. A group can then be treated as one object, enabling, for example, the moving of the primitives at the same time. Primitives can also be moved to front or back; this may have an effect if the primitives are on top of each other. •To group a set of primitives, select the first primitive and then shift-click to select the other primitives. Then select Graphics @ Operations @ Group. •To move a primitive to the front, select the primitive and then choose Graphics @ Operations @ Move To Front. ‡ Picking Coordinates

With the coordinate-picking tool

we can read and copy coordinates.

• To read coordinates, move the coordinate-picking tool on the plot (without pressing the mouse button).

132

Mathematica Navigator

•To mark a point, click, with the coordinate-picking tool, on the point. To mark several points on a path, drag with the coordinate-picking tool. To delete a marker, ‚-click (Ì-click on a Macintosh) on the marker. •To copy the coordinates of a point, mark the point and do standard copying; the coordinates can then be pasted. •To mark a rectangle, ‡-drag (ı-drag on a Macintosh). To copy the coordinates of two opposite corners of the marked rectangle, do standard copying; the coordinates can then be pasted. If marked points are inside the rectangle, their coordinates are also copied and pasted.

5.2 Other Plots for 2D Functions 5.2.1 Parametric Plots ParametricPlot[{fx, fy}, {t, a, b}] Make a parametric plot ParametricPlot[{{fx, fy}, {gx, gy}, … }, {t, a, b}] Make several parametric plots

We can define a function parametrically by giving a list of two expressions {fx, fy}. The expressions define the x and y coordinates of the function and are functions of a parameter, often denoted by t. The usual plotting command Plot[expr, {x, a, b}] can be seen as the special case ParametricPlot[{x, expr}, {x, a, b}] of the parametric plotting command. ParametricPlot has almost the same options and default values as Plot (the options are considered in detail in Chapter 7). One notable exception is the option AspectRatio. For Plot, the default value of this option is 1/GoldenRatio, whereas for ParametricPlot the default value is Automatic. For parametric plots, this default value is useful because, for example, a circle looks like a circle (see p1 below) and not like an ellipse. Here are some examples: [email protected], Ticks Ø NoneD; p1 = [email protected]@tD, [email protected]<, 8t, 0, 2 p
Chapter 5 • Graphics for Functions

133

With a rotation transform we can plot, for example, a rotated ellipse:

t =.; [email protected]@Pi ê [email protected] [email protected], [email protected]
1 -1

‡ Polar Plots PolarPlot[r, {q, a, b}] (Ÿ6) Make a polar plot

In a polar plot, the radius r is a function of angle q. A polar plotting command PolarPlot[r, {q, a, b}] is the special case ParametricPlot[{r Cos[q], r Sin[q]}, {q, a, b}] of the parametric plotting

command. Examples: [email protected], Ticks Ø NoneD;

p1 = [email protected], 8q, 0, 2 p
5.2.2 Logarithmic Plots LogPlot[f, {x, a, b}] (Ÿ6) A plot of Log[f] as a function of x LogLinearPlot[f, {x, a, b}] (Ÿ6) A plot of f as a function of Log[x] LogLogPlot[f, {x, a, b}] (Ÿ6) A plot of Log[f] as a function of Log[x]

With LogPlot, exponential functions become straight lines. With LogLinearPlot, logarithmic functions become straight lines. With LogLogPlot, power functions become straight lines. Logarithmic plots have the same options as Plot. [email protected]@xD, 8x, 0, 4<, GridLines Ø AutomaticD, [email protected]@xD, 8x, 1, 100<, GridLines Ø AutomaticD, [email protected] ^ H1 ê 2L, 8x, 1, 100<, GridLines Ø AutomaticD< 50

10.0 7.0 5.0

4

:

20 3

10

,

5

,

2

2.0 1.5

1

2 1

2

3

4

>

3.0

2

5

10

20

50

100

2

5

10

20

50 100

134

Mathematica Navigator

5.2.3 Implicit Plots ‡ Plotting an Implicit Function

An implicit function is defined by an equation expr1 ã expr2 (note the two equals signs needed in equations) in which the expressions are functions of two variables, often denoted by x and y. From the equation we can, at least in principle, solve y for each x, and so we get a function y of x. With ContourPlot, we can plot implicit functions (ContourPlot is considered in more detail in Sections 5.3.1, p. 139, and 7.6.1, p. 226). ContourPlot[expr1 ã expr2, {x, a, b}, {y, c, d}] (Ÿ6) Plot an implicit function defined by an

equation The default is that a contour plot has a frame, but we can ask not to draw a frame but, rather, the axes. Also, the default aspect ratio is 1 for a contour plot. [email protected] ^ 3 - 2 x y + y ^ 3 ã 0, 8x, -1.2, 1.1<, 8y, -1, 1.1<, PlotPoints Ø 40, Frame Ø False, Axes Ø True, AspectRatio Ø AutomaticD 1.0

0.5

-1.0

-0.5

0.5

1.0

-0.5

-1.0

Note that if you give a name for the equation, you need Evaluate in the plotting command: eqn = x ^ 3 - 2 x y + y ^ 3 ã 0;

[email protected] êê Evaluate, 8x, -1.2, 1.1<, 8y, -1, 1.1
Whereas ContourPlot plots the points satisfying an equality, RegionPlot (see Section 5.2.5, p. 136) plots regions where one or more inequalities are satisfied. ‡ Plotting a Function of an Implicit Function

We may have the situation in which y is defined implicitly as a function of x by an equation expr1 ã expr2 but we want to plot, by using x as the independent variable, not the plain y but an expression expr3 containing y (and possibly also x). In this way, expr3 is a function of the implicit function y.

As an example, consider the salmon model of Mesterton-Gibbons (1989, p. 62). In studying the stability of a period-2 equilibrium cycle, we have the following equation: eqn = y [email protected] H1 - yLD ã 2 - y;

This implicitly defines y for each r, and we want to plot the following expression as a function of r: delta = [email protected] - r yL H1 - 2 r + r yLD;

First, we plot the implicit function defined by eqn:

Chapter 5 • Graphics for Functions

135

[email protected] êê Evaluate, 8r, 1.9, 2.8<, 8y, 0, 2<, Frame Ø False, Axes Ø True, AxesOrigin Ø 81.9, 0<, PlotPoints Ø 40, AspectRatio Ø 1 ê GoldenRatioD 2.0 1.5 1.0 0.5 2.0

2.2

2.4

2.6

2.8

Thus, y as a function of r has multiple values. When plotting delta for r in H2, 2.8L, we are interested in the smallest y value. Plot delta as follows (we also plot the line 1 with the Epilog option): [email protected]@8r, y = y ê. [email protected] [email protected] H1 - yLD ã 2 - y, 8y, 0.1
2.2

2.4

2.6

2.8

In FindRoot, we used the starting value 0.1, for which we get the smallest y value (as can be verified). The stability of the cycle requires that delta be smaller than 1. From the previous plot, we see that r should be at most approximately 2.5. To get a more accurate value, we solve a system of two equations: [email protected] ã 1, eqn<, 8r, 2<, 8y, 0.1
8r Ø 2.52647, y Ø 0.277704<

5.2.4 Filled Plots ‡ Plotting One Curve with a Fill Filling (Ÿ6) Type of filling to use; examples of values: None, Axis, Bottom, Top, 0.3 FillingStyle (Ÿ6) Style of filling; examples of values: Automatic, Red, {Blue, Red} (different

style for negative and positive values), {{Opacity[0.3], Blue}} [email protected] [email protected]@xD, 8x, 0, 2 p<, Filling Ø ÒD & êü 8Axis, Bottom, Top, -0.5<, ImageSize Ø 420D

Next, we define custom styles:

136

Mathematica Navigator

[email protected]@[email protected], 8x, 0, 2 p<, Filling Ø Axis, FillingStyle Ø ÒD & êü 8Red, 8Blue, Red<, [email protected], Blue<<<, ImageSize Ø 310D

‡ Plotting Two Curves with Fills Filling (Ÿ6) Type of filling to use; examples of values: Axis (fills from the curves to the x axis), True (a fill between the curves), {1 Ø Axis} (a fill between the first curve and x axis), {2 Ø {1}} (a fill between the curves), {1 Ø {{2}, Red}} (define also the filling style), {1 Ø {{2}, Directive[Opacity[0.3], Red]}} (define style with several directives) FillingStyle (Ÿ6) Style of filling; examples of values: Red, {Blue, Red} (different styles depending on which curve is the topmost), {{Opacity[0.3], Blue}}

In filling, several directives have to be collected together with Directive. Examples:

[email protected]@[email protected], [email protected]<, 8x, 0, 2 p<, Filling Ø TrueD, [email protected]@xD, [email protected]<, 8x, 0, 2 p<, Filling Ø AxisD, [email protected]@xD, [email protected] ê 4 < x < 3 p ê 4, 0D<, 8x, 0, p<, Filling Ø 81 Ø 82<
5.2.5 Region Plots RegionPlot[ineqs, {x, a, b}, {y, c, d}] (Ÿ6) Show by a filled plot the region where the given

logical combination of inequalities are satisfied (i.e., gives True) RegionPlot has much the same options as ContourPlot. The style of the boundary of the region can be controlled with BoundaryStyle and the style of the fill with PlotStyle.

Inequalities can be combined with logical operations such as && (AND), || (OR), ! (NOT), or Xor (exclusive OR); these are explained in Section 13.3.5, p. 431. For example, [email protected], Frame Ø False, Axes Ø True, AspectRatio Ø AutomaticD;

p1 = [email protected] ^ 2 < y < [email protected], 8x, 0, 1<, 8y, 0, 1
Chapter 5 • Graphics for Functions

137

[email protected], p2, p3, p4<, ImageSize Ø 420D

‡ Parametric Region Plots ParametricPlot[{fx, fy}, {t, a, b}, {u, c, d}] (Ÿ6) Plot a parametrically defined region [email protected] [email protected], r [email protected]<, 8r, 1, 2<, 8q, 0, 2 p
:

,

,

>

5.2.6 Complex Plots ‡ Using Re, Im, and Abs

If the function to be plotted has complex values for some values of the argument, nothing is plotted for these values of argument: [email protected]@[email protected] - 0.5, 8x, 0, 2 p
-0.2

1

2

3

4

5

6

-0.4

One possibility to plot functions that have complex values is to use Re, Im, or Abs to plot only the real or imaginary part or the absolute value:

138

Mathematica Navigator

[email protected]@[email protected]@xDD - 0.5D, 8x, 0, 2 p
:

0.2

0.8

0.6

, -0.2

1.0

0.8

1

2

3

4

5

6

,

0.4

>

0.6 0.4

0.2

0.2

-0.4 1

2

3

4

5

6

1

2

3

4

5

6

‡ Complex Powers

Consider the function x1ê3 . For a given x such as -2.0, it takes on three values, which can be obtained by solving the equation y3 = -2.0: [email protected] ^ 3 ã -2.0D

88y Ø -1.25992<, 8y Ø 0.629961 - 1.09112 Â<, 8y Ø 0.629961 + 1.09112 Â<<

Let us look at what value Mathematica gives us for H-2L1ê3 : H-2.L ^ H1 ê 3L

0.629961 + 1.09112 Â

We have a complex value rather than the real value -1.25992. In general, Mathematica gives the value with the smallest positive argument. To plot a function such as x1ê3 , one possibility is to plot the implicitly defined function y3 = x: [email protected] ^ 3 == x, 8x, -2, 2<, 8y, -1.2, 1.2<, Frame Ø False, Axes Ø True, AspectRatio Ø 1 ê GoldenRatioD 1.0 0.5 -2

-1

1

2

-0.5 -1.0

‡ Region Plots RegionPlot[ineqs, {x, a, b}, {y, c, d}] (Ÿ6) Show by a filled plot the region where the given

logical combination of inequalities is satisfied (i.e., gives True) RegionPlot can also be used for inequalities with complex variables: [email protected], Frame Ø False, Axes Ø TrueD;

p1 = [email protected]@x + I yD § 1, 8x, -1, 1<, 8y, -1, 1
Chapter 5 • Graphics for Functions

139

[email protected], p2, p3, p4<, ImageSize Ø 420D

The last plot shows the region where the function

x3 - y is real.

‡ Contour and Parametric Plots ContourPlot[Abs[f], {x, a, b}, {y, c, d}] ParametricPlot[{Re[f], Im[f]}, {x, a, b}, {y, c, d}] (Ÿ6) f = 1 ê Hx + I yL; [email protected]@fD, 8x, -1, 1<, 8y, -1, 1
:

,

>

The package VectorFieldPlots` defines PolyaFieldPlot.

5.3 Plots for 3D Functions 5.3.1 Basic Plots ‡ Surface, Contour, and Density Plots Plot3D[f, {x, a, b}, {y, c, d}] Plot f as a surface plot ContourPlot[f, {x, a, b}, {y, c, d}] Plot f as a contour plot DensityPlot[f, {x, a, b}, {y, c, d}] Plot f as a density plot

Surface, contour, and density plots are the three main plot types to illustrate 3D functions. For example, f = [email protected] yD [email protected];

140

Mathematica Navigator

[email protected], 8x, 0, 3<, 8y, 0, 4<, AxesLabel Ø 8x, y, None
:

,

>

,

Plot3D shows a 3D surface. ContourPlot produces curves that are contours of constant value~that is, along each of the curves the value of the function is a certain constant. By moving the mouse pointer over a contour plot (without pressing the mouse button), we can see the constants corresponding to the contours. DensityPlot shows the highest parts of the function as light and the lowest parts as dark. All of these commands are adaptive (Ÿ6): They sample the function at more and more points until the plot is smooth enough. Note that only a surface plots is a true 3D plot; a contour or density plot is actually a 2D plot suitable to illustrate a 3D function.

We can show a surface with contours of constant value. We can also show several surfaces at the same time: [email protected], 8x, 0, 3<, 8y, 0, 4<, MeshFunctions Ø 8Ò3 &
:

,

>

In Section 5.2.3, p. 134, we considered the use of ContourPlot to plot implicitly defined functions. ‡ Mouse Manipulations

For 3D plots, we can perform similar manipulations with the mouse as we did for 2D plots (see Section 5.1.1, p. 120). First, click on the plot so that the selection rectangle appears. Then do the following: • To resize, drag by a handle of the selection rectangle; ˜ drag to change the aspect ratio. • To move, drag by an edge of the selection rectangle. • To crop, hold down the ‚ (Windows) or Ì (Macintosh) key and drag by a handle. • To go back to the standard position and size, choose Graphics @ Rendering @ Make Standard Size. In addition, we can rotate, zoom, and pan a plot produced by Plot3D: •To rotate, move the pointer over the plot. The pointer changes to the rotate pointer rotate.

. Drag to

Chapter 5 • Graphics for Functions

141

•To rotate about the axis perpendicular to the screen, move the pointer to a corner area of the plot. The pointer changes to the vertical rotate pointer

. Drag clockwise or counterclockwise to rotate.

•To zoom, hold down the ‚ (Windows) or Ì (Macintosh) key and drag with the zoom pointer upwards (to zoom in) or downwards (to zoom out). •To pan the 3D object~that is, to move it inside the selection rectangle~shift-drag the object with the pan pointer

.

Note that interactive drawing (Graphics @ Drawing Tools, Graphics @ Graphics Inspector) does not work with plots produced by Plot3D or by other surface plotting commands. Here is the Klein bottle:

a = 6 [email protected] H1 + [email protected]; b = 16 [email protected]; c = 4 H1 - [email protected] ê 2L; fx = [email protected] < u § 2 p, a + c [email protected] + pD, a + c [email protected] [email protected]; fy = [email protected] < u § 2 p, b, b + c [email protected] [email protected]; fz = c [email protected];

[email protected], fy, fz<, 8u, 0, 2 p<, 8v, 0, 2 p<, Boxed Ø False, Axes Ø FalseD

As an example of manipulating with the mouse, resize this plot larger and then rotate it to look inside the bottle. Try also zooming. ‡

Some Options

We consider all of the options of the main 3D graphics commands in Chapter 9. Here, we only mention two options: An option for Plot3D: BoxRatios Ratios of side lengths of the bounding box; examples of values: {1,1,0.4}, Automatic An option for ContourPlot and DensityPlot: AspectRatio Ratio of height to width of the plotting rectangle; examples of values: 1, Automatic The default value {1, 1, 0.4} of BoxRatios for Plot3D means that the x and y axes have the same length and that the length of the z axis is 0.4 times the length of the other axes. If we set BoxRatios Ø Automatic, then one unit on each of the x, y, and z axes has the same length in the surface plot. The default value 1 of AspectRatio for ContourPlot and DensityPlot gives a plot of a square form. If we set AspectRatio Ø Automatic, then one unit on both the x and y axes has the same length. Note that contour and density plots have a frame (and no axes), and so ticks on the frame can be set with FrameTicks.

142

Mathematica Navigator

5.3.2 Special Plots ‡ Parametric Plots ParametricPlot3D[{fx, fy, fz}, {u, a, b}] Plot a parametric curve ParametricPlot3D[{fx, fy, fz}, {u, a, b}, {v, c, d}] Plot a parametric surface

The expressions fx, fy, and fz give the x, y, and z coordinates of the curve or surface. [email protected], Axes Ø False, Boxed Ø FalseD;

p1 = [email protected], [email protected] uD, [email protected] uD<, 8u, 0, p<, PlotStyle Ø BlackD; p2 = [email protected] [email protected], v [email protected], 2 v<, 8u, 0, 2 Pi<, 8v, 0, 1
p6 = [email protected], p5<, PlotRange Ø AllD; p7 = [email protected] [email protected] H3 + [email protected], [email protected], [email protected] H3 + [email protected]<, 8u, 0, 2 p<, 8v, 0, 2 p
Like other plotting commands, ParametricPlot3D is adaptive. The default value of BoxRatios is Automatic (compared with {1, 1, 0.4} for Plot3D). This means that a parametric plot is shown in the

natural scaling, where one unit on the x, y, and z axes has the same length.

Chapter 5 • Graphics for Functions

143

‡ Spherical Plots SphericalPlot3D[r, {q, a, b}, {f, c, d}] (Ÿ6) SphericalPlot3D uses ParametricPlot3D with argument r{Sin[q] Cos[f], Sin[q] Sin[f], Cos[q]}. [email protected], Axes Ø False, Boxed Ø FalseD; [email protected], 8q, 0, p<, 8f, 0, 2 p
:

,

>

,

‡ Surfaces of Revolution

RevolutionPlot3D[fz, {t, a, b}] (Ÿ6) Rotate around z axis the curve fz in the Ht, zL plane RevolutionPlot3D[{fx, fz}, {t, a, b}] Rotate around z axis the parametrically defined curve RevolutionPlot3D[{fx, fy, fz}, {t, a, b}] Rotate around z axis the parametrically defined

space curve We can add a third argument {q, c, d} to these commands so that the curve is rotated only from angle c to angle d. [email protected], Axes Ø False, Boxed Ø FalseD;

[email protected]@tD, 8t, 0, 2 p
:

,

,

>

‡ Region Plots RegionPlot3D[ineqs, {x, a, b}, {y, c, d}, {z, e, f}] (Ÿ6) Show the region that satisfies the

given logical combination of inequalities

144

Mathematica Navigator

[email protected] x ^ 2 + y ^ 2 + z ^ 2 § 1, 8x, -1, 1<, 8y, -1, 1<, 8z, -1, 1<, Mesh Ø None, PlotPoints Ø 30D, [email protected] x ^ 2 + y ^ 2 + z ^ 2 § 1 && -x + y + z ¥ 0.05, 8x, -1, 1<, 8y, -1, 1<, 8z, -1, 1<, Mesh Ø None, PlotPoints Ø 60D, [email protected]@x ^ 2 + y ^ 2 + z ^ 2D ¥ 0, 8x, -1.5, 1.5<, 8y, -1.5, 0<, 8z, -1.5, 1.5<, Mesh Ø None, BoxRatios Ø AutomaticD<

:

,

,

>

The default value of BoxRatios for RegionPlot3D is {1, 1, 1}. Note that with ContourPlot3D we can plot surfaces of constant value (see Section 5.4.2, p. 149). ‡ Gradient Fields

In the VectorFieldPlots` package: VectorFieldPlot[{fx, fy}, {x, a, b}, {y, c, d}] (Ÿ6) Plot the vector field of the vector-valued

function {fx, fy} valued function f; that is, plot the vector field of Ix f , y f M

GradientFieldPlot[f, {x, a, b}, {y, c, d}] (Ÿ6) Plot the gradient vector field of the scalar-

scalar-valued function f; that is, plot the vector field of Iy f , -x f M

HamiltonianFieldPlot[f, {x, a, b}, {y, c, d}] (Ÿ6) Plot the Hamiltonian vector field of the

Special options (in addition to the options of Graphics): PlotPoints Number of evaluation points; examples of values: 15, {10, 15} ColorFunction Function to define the style of the vectors; examples of values: None, (Hue[0] &), (RGBColor[#, 0, 1 - #] &) ScaleFunction Function to use for rescaling the magnitude of the vectors; examples of values: None, (0.2 # &) MaxArrowLength Eliminates vectors that are longer than the specified value (applied after ScaleFunction); default value: None (no vectors are removed) ScaleFactor Lengths of vectors are linearly scaled so that the length of the longest vector is equal

to the specified value (applied after MaxArrowLength); examples of values: Automatic (fits the vectors in the mesh), None (no rescaling is used; use this value with ScaleFunction) Plotting a gradient field is a way to describe a 3D function. The gradient points to the direction of maximum increase of the function. << VectorFieldPlots` f = [email protected] yD [email protected];

Chapter 5 • Graphics for Functions

145

[email protected], 8x, 0, 3 p ê 4<, 8y, 0, p ê 2<, ImageSize Ø 190D, [email protected], 8x, 0, 3 p ê 4<, 8y, 0, p ê 2<, PlotPoints Ø 10, ImageSize Ø 210D<

:

,

>

Plots of vector fields are handy in describing differential equations (see Sections 26.1.1, p. 832, 26.1.3, p. 839, and 26.3.2, p. 854) and difference equations (see Sections 28.1.1, p. 926, 28.1.2, p. 930, and 28.2.1, p. 937). f =.

5.3.3 Stereograms ‡ Two-Image Stereograms

An excellent 3D impression can be obtained by making two plots with slightly different viewpoints and placing the plots on top of each other using the eyes. Many of you are probably able to do this. For most people, it is easiest to try to focus beyond the paper surface. First, you get four plots, and the goal is to relax the eyes so much that two of the four plots are superimposed. The result is three plots, with the one in the middle giving the stereo view of the plot. For example, p1 = [email protected] [email protected] [email protected], s [email protected] [email protected], -s [email protected]<, 8s, 0, 2 p<, 8t, 0, p<, Axes Ø False, Boxed Ø FalseD;

p2 = [email protected], ViewPoint Ø 81.4, -2.3, 2.0
[email protected], p2<, Spacings Ø -140, ImageSize Ø 8400, 180<, PlotRegion Ø 88-0.08, 0.92<, 8-0.4, 1.1<
146

Mathematica Navigator

Here the first plot has the default viewpoint {1.3, -2.4, 2.0}. The other viewpoint {1.4, -2.3, 2.0} is at the same height (2.0) but the x and y coordinates are somewhat different. We showed the two

figures very near to each other. For the stereographic method to be possible to the eyes, the distance of two corresponding points in the two plots should be at most approximately 4 or 5 cm. The pair of figures we have considered gives the correct result if you focus your eyes beyond the paper. For some people, it is easier to focus on the front of the paper surface. In this case, the order of the figures has to be changed to get the correct result. For surfaces, the improvement in the illusion of three dimensions is clear with two-image stereograms but not so remarkable as for curves, dots, and arrows in space. For these latter graphics objects, if plotted in the usual way, the eye has too few guides to obtain an adequate impression of the positions of the objects, but the stereo view makes a major improvement. For examples of arrows and space curves, see Sections 5.4.1, p. 149 (gradient field of a 4D function), and 26.3.3, p. 864 (solution of a system of three differential equations). ‡ Single-Image Stereograms

Single-image (or random-dot) stereograms are explained in Maeder (1995a). The package of this article can be downloaded from the website www.mathematica-journal.com/backissues . From there, click “Vol. 5 (1)” and download the electronic supplement of this issue. See Section 4.1.3, p. 99, to learn about the correct place to put the SIS.m package. The SIS-EX.MA notebook contains some examples. In the SIS.m package: SIS[expr, {x, a, b}, {y, c, d}] Produce a single-image stereogram from the given function by

looking from the positive z axis Options: PlotRange Expected range of the function; default value: {0,1} PlotPoints Number of random initial points; default value: 100 PlaneDistance Distance from the back plane to the viewing plane; default value: 2 EyeDistance Distance from the viewing plane to the eyes; default value: 2 Guides Whether guide dots at the top of the plot are drawn; possible values: True, False EyeSeparation Separation of the guide dots measured as a fraction of half of the horizontal width

of the plot; default value: 1/4 Object Objects used in the plot; default value: Point PlotStyle Style of the objects; default value: {PointSize[0.01]}

As an example, we produce a single-image stereogram of the following function: [email protected]@[email protected] ^ 2 + y ^ 2DD, 8x, -7, 7<, 8y, -7, 7
<< SIS.m

Chapter 5 • Graphics for Functions

147

[email protected]@[email protected] ^ 2 + y ^ 2DD, 8x, -7, 7<, 8y, -7, 7<, PlotPoints Ø 150, PlotRange Ø 8-1, 1<, ImageSize Ø 200D

The top of the plot contains two dots as guides for the eyes. You get the stereographic view if you can get from the two dots~by focusing beyond the paper surface~first four dots and then three dots (two of the four dots are then superimposed). We have presented the plot in a small size; enlarge the plot to have a more impressive experience.

5.4 Plots for 4D Functions 5.4.1 Simple Methods 2D, 3D, and 4D functions are of the forms y = f HxL, z = f Ix, yM, and v = f Ix, y, zM, respectively. For 2D and 3D functions, we can use 2D and 3D graphics; for example, use Plot or Plot3D. Graphical illustration of 4D functions involves difficulties, but something can be done with 3D and even 2D graphics. ‡ Plotting Values on Curves and Surfaces

Consider the following function: [email protected]_, y_, z_D := [email protected] ^ 2 + y ^ 2 + z ^ 2D

With 2D graphics, we can show the values of the function along parametrically defined curves. For example, along the curves x = t, y = z = 0; x = y = t, z = 0; x = y = z = t; and x = cosHtL, y = sinHtL, z = 0, the value of the function is as follows:

p1 = [email protected]@t, 0, 0D, 8t, -1.5, 1.5<, PlotRange Ø 1, BaseStyle Ø 6D; p2 = [email protected]@t, t, 0D, 8t, -1.5, 1.5<, PlotRange Ø 1, BaseStyle Ø 6D; p3 = [email protected]@t, t, tD, 8t, -1.5, 1.5<, PlotRange Ø 1, BaseStyle Ø 6D; p4 = [email protected]@[email protected], [email protected], 0D, 8t, -1.5, 1.5<, PlotRange Ø 1, BaseStyle Ø 6D;

148

Mathematica Navigator

[email protected], p2, p3, p4<, ImageSize Ø 420, BaseStyle Ø 5D 1.0

1.0

1.0

1.0

0.5

0.5

0.5

0.5

-1.5 -1.0 -0.5 -0.5

0.5

1.0

1.5

-1.5 -1.0 -0.5 -0.5

-1.0

0.5

1.0

1.5

-1.5 -1.0 -0.5 -0.5

-1.0

0.5

1.0

1.5

-1.5 -1.0 -0.5 -0.5

-1.0

0.5

1.0

1.5

-1.0

example, on the surface x = u, y = v, z = 0 [i.e., on the Ix, yM plane], the value of the function is as follows:

With 3D graphics, we can show the values of the function on parametrically defined surfaces. For [email protected]@u, v, 0D, 8u, -1.5, 1.5<, 8v, -1.5, 1.5
The properties of the first, second, and fourth 2D plots can also be seen (or at least guessed) from this single plot. ‡ Gradient Fields

In the VectorFieldPlots` package: VectorFieldPlot3D[{gx, gy, gz}, {x, a, b}, {y, c, d}, {z, e, f}] (Ÿ6) Plot the vector field of

the vector-valued function {gx, gy, gz} the scalar-valued function g; that is, plot the vector field of Ix g, y g, z gM

GradientFieldPlot3D[g, {x, a, b}, {y, c, d}, {z, e, f}] (Ÿ6) Plot the gradient vector field of

Special options (in addition to the options of Graphics3D): PlotPoints, ColorFunction, ScaleFunction, MaxArrowLength, ScaleFactor, VectorHeads These commands have the same five options as the corresponding 2D commands (see Section 5.3.2, p. 144) plus the option VectorHeads. This new option can be used to tell whether the vectors should have a head (True) or not (False, the default). PlotPoints now has the default value 7; the value must be a single number. One method for illustrating a 4D function is to plot the gradient field. The gradient points in the direction of maximum increase of the function. The longer the arrow, the stronger the growth. The heads of the arrows show the direction of growth. As an example, consider the same function as we studied previously and generate a two-image stereogram: << VectorFieldPlots`

p1 = [email protected]@x ^ 2 + y ^ 2 + z ^ 2D, 8x, -1.5, 1.5<, 8y, -1.5, 1.5<, 8z, -1.5, 1.5<, PlotPoints Ø 5, VectorHeads Ø TrueD;

p2 = [email protected], ViewPoint Ø 81.4, -2.3, 2.0
Chapter 5 • Graphics for Functions

149

[email protected], p2<, Spacings Ø -20, ImageSize Ø 320D

Near the boundary of the box, the function grows toward the outside; in the middle of the box, it grows toward the inside. This means that where the directions of the arrows change, the function has a surface of local minimum points.

5.4.2 Surfaces of Constant Value With ContourPlot, we can plot curves of constant value for a 3D function z = gIx, yM. With ContourPlot3D, we can plot surfaces of constant value for a 4D function v = gIx, y, zM. ContourPlot3D[g, {x, a, b}, {y, c, d}, {z, e, f}] Plot some surfaces of constant value of g ContourPlot3D[g ã h, {x, a, b}, {y, c, d}, {z, e, f}] Plot the surfaces where g ã h

Special options (in addition to the options of Plot3D): Contours How many or what surfaces are drawn; examples of values: Automatic, 3, {0, 1, 2} ContourStyle Style of the surfaces; examples of values: GrayLevel[1], Opacity[0.8], {Red, Green}

The command has mostly the same options as Plot3D. Two new options are Contours and boundaries of the surfaces. BoxRatios has the default value 81, 1, 1<.

ContourStyle (PlotStyle does not exist). BoundaryStyle can be used to define the style of the

By default, the command automatically chooses some constants for which the corresponding surfaces are plotted. The option Contours can be given either a constant value, telling how many surfaces are plotted, or a list of constants, telling the constants for which surfaces are plotted. Because the surfaces of constant value tend to give somewhat complex plots, it may be useful to plot separate figures for each value of the constant. Plotting surfaces of constant value is a demanding task, so the computation time may be somewhat large. When experimenting with the command (so that the quality of the plot need not be high), the MaxRecursion option can be given a small enough value such as 0 to reduce the computation time. Also, PlotPoints can be given a small value such as 10. However, this may cause some surfaces to be missed. When producing the final plot, these options can be given higher values or the options can be dropped altogether to get a high-quality plot. ContourStyle can be useful to identify the surfaces if several are plotted at the same time; opacity may be useful to see surfaces behind other surfaces.

150

Mathematica Navigator

As an example, we consider the same function as in Section 5.4.1, p. 147. We ask for the surfaces where the function has the value -0.5, 0, and 0.5:

[email protected]@x ^ 2 + y ^ 2 + z ^ 2D ã Ò, 8x, -1.5, 1.5<, 8y, 0, 1.5<, 8z, -1.5, 1.5<, ContourStyle Ø [email protected], Mesh Ø None, BoxRatios Ø Automatic, MaxRecursion Ø 0D & êü 8-0.5, 0, 0.5<

:

,

,

>

The function seems to grow when the argument approaches the origin but also when the argument moves near the corners of the bounding box. For another example of surfaces of constant value, see Section 27.2.6, p. 909, in which we plot the solution of a 3D elliptic partial differential equation. Remember that with RegionPlot3D, we can plot 3D regions:

[email protected]@x ^ 2 + y ^ 2 + z ^ 2D ¥ 0, 8x, -1.5, 1.5<, 8y, 0, 1.5<, 8z, -1.5, 1.5<, Mesh Ø None, BoxRatios Ø AutomaticD

6 Graphics Primitives Introduction 151 6.1 Introduction to Graphics Primitives 152 6.1.1 Introduction 152 Graphics, FullGraphics 6.1.2 Summary 154 Point, Line, Thickness, Directive, etc. 6.2 Primitives and Directives 155 6.2.1 Point 155 Point, PointSize, AbsolutePointSize 6.2.2 Line 156 Line, Thickness, AbsoluteThickness, Dashing, AbsoluteDashing 6.2.3 Circle and Ellipse 159 Circle 6.2.4 Transformations 160 Rotate, GeometricTransformation, RotationTransform, etc. 6.2.5 Arrow and Spline 161 Arrow, Arrowheads, Spline 6.2.6 Text and Coordinates 163 Text, Style, FontFamily, FontColor, Scaled, Offset, etc. 6.2.7 Rectangle, Polygon, and Disk 166 Rectangle, Polygon, Disk, EdgeForm, FaceForm 6.2.8 Colors and Raster 168 GrayLevel, Hue, RGBColor, Opacity, Blend, Raster, etc. 6.2.9 GraphicsComplex 173 GraphicsComplex 6.2.10 Inset 175 Inset, GraphicsGroup 6.2.11 3D Primitives and Directives 176 Graphics3D, Cuboid, Sphere, Cylinder, Specularity, etc.

Introduction In the fourth century B.C., Alexander the Great asked his teacher, Menaechmus, for a shortcut to geometry and received the reply “Oh, King, for travelling over the country, there are royal roads for kings, but in geometry there is one road for all.” For producing graphics, commands such as Plot or ListPlot are the ones we use most often. However, these commands do not cover all graphics. For example, for various geometric figures we need other techniques in which we can gather the plot from basic components such as points, lines, circles, and arcs. Graphics is a command designed to build plots from so-called graphics primitives. We have such primitives as Point, Line, Circle, Arrow, Text, and Rectangle. The styles of the primitives can be adjusted with so-called graphics directives. We have such directives as PointSize, Thickness, Dashing, GrayLevel, RGBColor, and Opacity. Building plots from scratch with Graphics is one use of the primitives and directives. This may also be called graphics programming. We consider programming in Chapter 18, but graphics programming is covered in this chapter.

Another use of the directives is in enhancing usual plots with options such as PlotStyle: In defining a style, we use directives. Also, with the Prolog and Epilog options we can add primitives to usual plots. The importance of the primitives and directives is even more clear considering the fact that all plots in Mathematica are made up of these components (although we usually do not see them).

152

Mathematica Navigator

6.1 Introduction to Graphics Primitives 6.1.1 Introduction ‡ Importance of Primitives and Directives

All plots in Mathematica are made up of a few basic components called graphics primitives. We have such primitives as Point, Line, Circle, Rectangle, and Text. The style of these primitives is controlled with graphics directives such as PointSize, Thickness, Dashing, GrayLevel, or RGBColor. The importance of the primitives and directives derives from three facts: •Mathematica uses the primitives and directives in the construction of all plots. •We can construct a plot directly from the primitives and directives (this can be called graphics programming). •The primitives and directives can be used to modify plots with options. In practice, the third fact is the most important. Indeed, all plotting commands have several options, such as PlotStyle, to modify the plot with directives (e.g., PlotStyle Ø Thickness[0.02]). In addition, with the Prolog and Epilog options, we can add primitives to plots (e.g., Epilog Ø {Thickness[0.02], Line[{{0, 1}, {2, 1}}]}). Options are considered in Chapter 7. Examples 1 and 2 illustrate the first and second facts. ‡ Example 1

Here is a very simple plot:

p = [email protected], 8x, 0, 4<, Ticks Ø 884<, None<, PlotPoints Ø 3, MaxRecursion Ø 0D

4

With InputForm, we can see how Mathematica made the plot: [email protected]<, 8<, [email protected], 0.6, 0.6D, [email protected]*^-6, 1.<, 81.9236087977499787, 1.<, 83.999998, 1.<>
[email protected]@pD, 3.5D

(We showed only the basic part of p; seven options are not shown.) We see that the line is drawn with the Line primitive. It goes through three points. The color of the line is set with a Hue directive. Graphics then creates a graphics object from the directive and primitive. The front end automatically displays a graphics object as graphics. With FullGraphics, we can see all the graphics primitives of a plot, including the primitives used for axes and ticks, among other things:

Chapter 6 • Graphics Primitives

153

[email protected]@[email protected], 8D

[email protected]<, 8<, [email protected], 0.6, 0.6D, [email protected]*^-6, 1.<, 81.9236087977499787, 1.<, 83.999998, 1.<
Here we first see the line. Then we have the tick mark and the tick label 4 on the x axis, and lastly we can see the two lines forming the axes. ‡ Example 2

Usually, it is most practical to use commands such as Plot, but if we so choose, we can collect a plot from graphics primitives. As an example, we make the same plot as we made previously, with slight simplification: [email protected]@880, 1<, 84, 1<
4

This is a small example of graphics programming: the building of graphics from primitives. ‡ Building Plots from Primitives and Directives

The examples show that we get a graphics object from the primitives with Graphics. Graphics[{directives and primitives}, options] Create and show a graphics object from directives

and primitives, using some options All primitives have their default styles. If these are used, we need not define directives; we simply write a list of primitives (as in Example 2). We can modify each primitive with one or more directives. They are written before the corresponding primitive and thus work like adjectives. However, note that a directive affects all primitives after the directive. Thus, if you want to apply a directive or several directives only to the next primitive, enclose the directives and the primitive in curly braces ( { }), as seen in the following example: Graphics[{{dir11 , dir12 , …, prim1 }, {dir21 , dir22 , …, prim2 }, … }] Graphics has many of the options of Plot and most default values are the same for these commands. Some exceptions are as follows. For Graphics we have AspectRatio Ø Automatic, Axes Ø False, PlotRange Ø All, and PlotRangeClipping Ø False,

whereas for Plot we have AspectRatio

Ø

1/GoldenRatio,

PlotRangeClipping Ø True.

Axes

Ø

True,

PlotRange

Ø

{Full,

Automatic},

and

154

Mathematica Navigator

Graphics does not have certain options that Plot does, which control the sampling algorithm.

With the Prolog and Epilog options, we can add graphics primitives to plots produced by usual plotting commands such as Plot (see Section 7.3.6, p. 201): Plot[f, {x, a, b}, Epilog Ø {directives and primitives}] Add graphics primitives

6.1.2 Summary ‡ Graphics Primitives

The following are all the built-in 2D graphics primitives and one primitive from a package. With p, p1, p2, and pn we denote a point, made up of the x and y coordinates, such as {1, 4}. For a mathematician, the primitives Point, Line, Circle, Arrow, and Text may be the most important. Point[p] Point at p Line[{p1, …, pn}] Line through points p1, ..., pn Circle[p, r] Circle with center p and radius r (also ellipse) Arrow[{p1, p2}] (Ÿ6) Arrow from p1 to p2 Spline[{p1, …, pn}, type, opts] Spline through points p1, ..., pn Text[expr, p, opts] Text expr centered at p Rectangle[p1, p2] Filled rectangle with two opposite corners at p1 and p2 Polygon[{p1, …, pn}] Filled polygon with vertices p1, ..., pn Disk[p, r] Filled disk with center p and radius r (also filled ellipse) Raster[colors] Raster image Spline is defined in the Splines` package. Note that GraphicsComplex, Inset, and GraphicsGroup, considered in Sections 6.2.9 and 6.2.10, can also be used like primitives. In addition, in Section 10 we encounter Locator, a graphics primitive useful in dynamic graphics.

In Section 6.2, we consider all the 2D primitives. 3D primitives are addressed in Section 6.2.11, p. 176. In Section 7.3.6, p. 201, and in numerous other sections, we present other examples of using graphics primitives. ‡ Graphics Directives

Here are the most important graphics directives: PointSize[d], AbsolutePointSize[d] Thickness[d], AbsoluteThickness[d] Dashing[{d1, d2, … }], AbsoluteDashing[{d1, d2 ,… }] Arrowheads[s] EdgeForm[dirs], FaceForm[dirs] GrayLevel[g] Gray g Hue[h] Hue h RGBColor[r, g, b] Red r, green g, and blue b CMYKColor[c, m, y, k] Cyan c, magenta m, yellow y, and black k Opacity[o] Opacity o

Chapter 6 • Graphics Primitives

155

Each primitive can be modified with certain directives. A summary is provided here. With Raster, we can use no directives. The opacity and color of all other graphics primitives can be defined with Opacity and with one of GrayLevel, Hue, RGBColor, and CMYKColor, or with special colors (e.g., Red); colors are considered in Section 6.2.8, p. 168. Color and opacity are the only directives that can be used with Text. In addition to opacity and color, the style of Rectangle, Polygon, and Disk can be controlled with EdgeForm and FaceForm. In addition to opacity and color, the style of a point can be controlled with PointSize or AbsolutePointSize and the style of a line, circle, arrow, and spline with Thickness or AbsoluteThickness and Dashing or AbsoluteDashing or with special thickness or dashing specifications (e.g., Thick or Dashed). Arrow also has the special directive Arrowheads, and Spline and Text have some special options. With Directive, we can collect together several directives and use the collection like a single directive: Directive[dir1, dir2, … ] (Ÿ6) Represents a single graphics directive composed of the given

directives In various options for styles such as PlotStyle, AxesStyle, FrameStyle, MeshStyle, or FillingStyle, the use of Directive may be helpful in simplifying the use of braces.

6.2 Primitives and Directives 6.2.1 Point Point[p] A point at p Point[{p1, …, pn}] (Ÿ6) Points at p1, …, pn

With Point, we can easily get the same result as with ListPlot: t = [email protected], [email protected]<, 8x, 0, 2 p, p ê 5
[email protected], [email protected]@tD, Axes Ø True, AspectRatio Ø 1 ê GoldenRatioD< 1.0

:

1.0

0.5

0.5

, 1

2

3

4

5

6

1

-0.5

-0.5

-1.0

-1.0

2

3

4

5

6

>

Using Graphics is, indeed, a noteworthy method to use to plot data, particularly in some more complex situations, and we will use it again in Chapter 8. ‡ PointSize PointSize[d] The diameter of a point is a fraction d of the width of the graph AbsolutePointSize[d] The diameter of a point is a multiple d of 1/72 inch Tiny, Small, Medium, Large (Ÿ6) Special values of d (they correspond approximately to absolute

point sizes 0, 2, 4.5, and 7)

156

Mathematica Navigator

The diameter of a point can be defined in two ways: either as a fraction of the width of the graph or as a multiple of the printer’s point, which is approximately 1/72 inch. For those of us more familiar with millimeters, we note that 3 printer points is approximately 1 millimeter. The default point size is AbsolutePointSize[3]. In addition, we can use such point sizes as PointSize[Small] (it is approximately the same as AbsolutePointSize[2]). Note that when a notebook is printed, the size of graphics is reduced to 80% so that the absolute sizes do not exactly hold on paper. The size of a point defined by PointSize depends on the size of the plot: The larger the plot, the larger the points (however, this does not hold for point sizes defined by Tiny, etc.). On the other hand, the size of a point defined with AbsolutePointSize does not depend on the size of the plot. In the following points, the absolute diameter varies from 1 to 7: [email protected]@[email protected], [email protected], 0
6.2.2 Line Line[{p1, p2}] A straight line between points p1 and p2 Line[{p1, …, pn}] A broken line through points p1, …, pn Line[{{p11, …, p1n}, {p21, …, p2n}, … }] (Ÿ6) Several broken lines

With Line, we can easily mimic ListLinePlot:

t = [email protected], [email protected]<, 8x, 0, 2 p, p ê 5
[email protected], [email protected]@tD, Axes Ø True, AspectRatio Ø 1 ê GoldenRatioD< 1.0

:

0.5

0.5

, 1

2

3

4

5

1

6

2

3

4

5

6

>

-0.5

-0.5

-1.0

With Point and Line, we can easily show both the points and the connecting lines between them: [email protected], Mesh Ø AllD, [email protected]@tD, [email protected]<, Axes Ø True, AspectRatio Ø 1 ê GoldenRatioD< 1.0

:

0.5

0.5

, 1 -0.5

2

3

4

5

1

6 -0.5 -1.0

2

3

4

5

6

>

Chapter 6 • Graphics Primitives

157

‡ Thickness Thickness[d] The thickness of a line is a fraction d of the width of the graph AbsoluteThickness[d] The thickness of a line is a multiple d of 1/72 inch Tiny, Small, Medium, Large (Ÿ6) Special values of d (they correspond approximately to absolute

thickness 0.2, 0.5, 1.1, and 1.9) Thin, Thick (Ÿ6) Special thickness specifications (they correspond approximately to absolute

thickness 0.2 and 1.9) The default thickness is AbsoluteThickness[0.5]. Thickness defined by Thickness depends on the size of the plot: The larger the plot, the thicker the curves. Thickness defined with AbsoluteThickness does not depend on the size of the plot. In the following plot, the absolute thickness varies from 0 to 3 in steps of 0.5: [email protected]@[email protected], [email protected], d<, 81, d<
As can be seen, the ends of a line float somewhat outside of the intended interval and do so more as the line becomes thicker. ‡ Dashing Dashing[{d1, d2, … }] The length of a segment is a fraction di of the width of the graph AbsoluteDashing[{d1, d2, … }] The length of a segment is a multiple di of 1/72 inch Tiny, Small, Medium, Large (Ÿ6) Special arguments of Dashing and AbsoluteDashing (they

correspond approximately to absolute dashing {1, 3}, {2.5, 4.5}, {5, 7}, and {10, 13}) Dotted, Dashed, DotDashed (Ÿ6) Special dashing specifications (they correspond approximately to

absolute dashing {1, 4}, {4, 4}, and {1, 4, 4, 4}) In the dashing style, a line consists of small segments, and they alternate between black and white. The lengths of the segments are defined with the dashing directive. Usually, only a few segments are defined, and they are used cyclically. For example, Dashing[{}] No dashing is used; lines are solid (this is the default) Dashing[{d, d}] or Dashing[{d}] or Dashing[d] Black and white segments, each of length d,

alternate Dashing[{d1, d2}] Black and white segments of lengths d1 and d2, respectively, alternate

Dashing defined with Dashing depends on the size of the figure: The larger the figure, the longer the segments. Dashing defined with AbsoluteDashing does not depend on the size of the figure. Next, we show absolute dashings between 2 and 4 in steps of 0.5:

158

Mathematica Navigator

[email protected]@[email protected], [email protected], d<, 81, d<
Note that the dashing is not exactly what we would expect: The white segments are smaller than they should be. The thicker the dashed curve, the smaller the white segments. This is a consequence of the fact that the ends of lines float outside of the desired interval, as we saw previously when we considered thickness. By the way, this problem with dashing may actually be a useful feature: The dashing looks better when the white parts are shorter than the black ones. If the length of a segment is 0, such a segment is drawn as a dot whose diameter is the thickness of the line: [email protected]@84, 2, 0, 2
‡ Regular Polygons

With Line, we can easily create regular polygons. Here is a function for doing this: [email protected]_, x0_, y0_, r_, q_, opts___D := [email protected]@8r [email protected]ÒD + x0, r [email protected]ÒD + y0< & êü [email protected], q + 2 p, 2 p ê nDD, optsD

The arguments of this function are the order n of the polygon, the center point (x0, y0), the radius r (from the center point to a vertex), an angle q (one of the vertices is at this angle), and zero or more options. To show, for example, a triangle, type regularPolygon[3, 0, 0, 1, p/2]. Here are some examples: g1 = [email protected], 0, 0, 1, p ê 2D; g2 = [email protected], 0, 0, 1, -p ê 2D; g3 = [email protected], 0, 0, 1, -pD; g4 = [email protected], 0, 0, 1, 0D; g5 = [email protected], 0, 0, 1, p ê 4D; g6 = [email protected], 0, 0, 1, 0D; [email protected], g2, g3, g4, g5, g6<, ImageSize Ø 240D

With the Polytopes` package, we can get information about regular polygons, from Digon to Dodecagon.

Chapter 6 • Graphics Primitives

159

6.2.3 Circle and Ellipse Circle[p] Circle with center p and radius 1 (Circle[] means Circle[{0,0}]) Circle[p, r] Circle with center p and radius r Circle[p, Offset[{r, r}]] Circle with center p and radius r/72 inch Circle[p, r, {q1, q2}] Circular arc Circle[p, {rx, ry}] Ellipse with center p and semi-axes of lengths rx and ry, oriented parallel to

the coordinate axes Circle[p, {rx, ry}, {q1, q2}] Elliptical arc

Consider the following circles: c1 = [email protected]@DD; c2 = [email protected]@D, AspectRatio Ø 0.5D; c3 = [email protected]@80, 0<, [email protected], 18
In the first plot, the aspect ratio has the default value Automatic; the circle looks like a circle. In the second plot, the aspect ratio is 0.5; the circle looks like an ellipse. In the third plot, the aspect ratio is again 0.5, but now the radius is defined with Offset; the circle again looks like a circle. Thus, to get true circles, either use AspectRatio Ø Automatic or define the radius with Offset. The difference between these methods is that if we change the size of a plot containing a circle, the size of the circle also changes in the first method but remains fixed in the second method. Circles can be used in plotting data:

data = [email protected], [email protected]<, 8i, 0, 40
[email protected]@dataD, [email protected]Ò, [email protected], 1.5


20

30

40

Later, we will use Disk in the same way. The use of Disk has the advantage that it enables us to hide the lines inside the circles. Circular arcs can be used to denote angles:

160

Mathematica Navigator

p =.; [email protected]@MediumD, [email protected], 1
a

6.2.4 Transformations Rotate[prim, q] (Ÿ6) Rotate the primitive counterclockwise by q radians about the center point Rotate[prim, q, p] Rotate about the given point GeometricTransformation[prim, transf] (Ÿ6) Apply the given transformation function GeometricTransformation[prim, mat] Multiply by the given matrix

In addition to Rotate, we also have Translate and Scale. Graphics primitives can be transformed in many ways. We have such transformation functions as Affine|, LinearFractional|, Reflection|, Rescaling|, Rotation|, Scaling|, Shearing|, and TranslationTransform. Examples: [email protected]@80, 0<, 84, 1
:

1

1.0 0.5 -4

-2

-0.5 -1.0

2

2

4

,

-3

-2

1

,

-1

1

2

3

-3

-2

-1

1

-1

-1

-2

-2

2

3

>

The next example shows how we can manipulate a circle by two vectors (Manipulate is considered in Chapter 10): ManipulateA [email protected], [email protected], 0
PlotRange Ø 5, ImageSize Ø 130E, 88v1, 83, 4<<, Locator<, 88v2, 8-3, -1<<, Locator
In the RegressionCommon` package, we also have the primitive Ellipsoid.

Chapter 6 • Graphics Primitives

161

6.2.5 Arrow and Spline ‡ Arrow Arrow[{p1, p2}] (Ÿ6) Arrow from point p1 to point p2 Arrow[{p1, p2}, d] The ends of the arrow are set back from p1 and p2 by a distance d Arrow[{p1, p2}, {d1, d2}] Sets back by d1 from p1 and by d2 from p2

A directive: Arrowheads[s] (Ÿ6) Length of the arrowhead is a fraction s of the width of the whole plot Arrowheads[{{s, pos}}] Arrowhead is of size s at position pos Arrowheads[{{s, pos, g}}] Arrowhead is graphic g Arrowheads[{{s, pos, {g, d}}] Shorten the shaft by d at the arrowhead end Arrowheads[{-s, s}] Double-headed arrow with heads of size s Arrowheads[{{-s1, pos1}, {s2, pos2}}] Double-headed arrow with custom sizes and positions

Note that by choosing Graphics @ Graphics Inspector, we get a window for specifying various styles. To give an arrow a suitable form, select the arrow on your plot and choose a suitable arrowhead from the 2D graphics inspector. The default length of the arrowhead (the default value of s) is 0.04. The head size s can also be Tiny, Small, Medium, or Large. The position of the vertex of the arrowhead runs from 0 to 1.

[email protected]@880, 0<, 80, 1<
The first arrow is in the default form, the second has a modified head size, and the third has a modified head size and position. The fourth arrow is double-headed. Now we create some custom arrowheads:

[email protected] = [email protected]@88-1, 1 ê 3<, 80, 0<, 8-1, -1 ê 3<
A custom arrowhead is placed so that the origin {0, 0} of its coordinates lies at the given position pos.

162

Mathematica Navigator

[email protected]@880.1, 1, h1<
If we connect circles with arrows, it may be helpful to set back the ends of the arrow by a distance that is the radius of the circle: [email protected]@80, 0<, 1D, [email protected], 0<, 1D, [email protected], 0<, 84, 0<
:

,

>

An arrow may sometimes be useful in pointing out some properties of a plot:

[email protected]@xD, 8x, 0, 2 p<, Ticks Ø 88p, 2 p<, 8-1, 1<<, PlotRange Ø 8Full, All<, ImageSize Ø 140, Epilog Ø [email protected]"point of inflection", 83.7, 0.45<, 8-1, -1
p

2p

-1

With the following program, we can easily define labeled arrows. [email protected]_, p2_<, label_, d_: 0, s_: 0.04D := [email protected] = [email protected]@[email protected], SmallD, 80, 0<, 80, -1.5
Note that here we defined that in the middle of the arrow we have a custom “arrowhead,” the label. The arguments d and s have the default values 0 and 0.04; if these values are suitable, the arguments d and s need not be written. [email protected]@80, 0<, 1D, [email protected], 3<, 1D, [email protected], 0<, 88, 3<<, "label", 1, 0.07D
l labe

Chapter 6 • Graphics Primitives

163

‡ Spline

In the Splines` package: Spline[{p1, p2, … }, type] Spline of type through (or controlled by) p1, p2, …

An option: SplineDots The style used for the given points; examples of values: None (points are not plotted), Automatic (points are red and of size 0.03)

For the Splines` package, look at SplinesêguideêSplinesPackage` in the Documentation Center. Splines are considered in detail in Section 24.3, p. 803. Here, we only note that a spline is a smooth curve through all or some of the points and that three types of splines can be used: Cubic (goes through all points), Bezier (goes through the end points), and CompositeBezier (goes through every other point). The default is that the given points are not shown. The splines are drawn by an adaptive method, which can be controlled with the additional options SplinePoints, MaxBend, and SplineDivision. Splines may be useful, for example, for drawing some arcs: << Splines` [email protected]@80, 0<, 1D, [email protected], 0<, 1D, [email protected], 0<, 1D, [email protected], 80, 0
1

2

3

6.2.6 Text and Coordinates ‡ Text Text[expr, {x, y}] The center of the text expr is at the point {x, y} Text[expr, {x, y}, {u, v}] The point {u, v}, expressed in text coordinates, of the text is at the

point {x, y} The expression to be printed can be a mathematical expression such as Sin[x] or a string such as "Here is text". The expression in printed, by default, in TraditionalForm. The default is that the text

is centered at the given point. However, a text element has its own coordinate system ranging from -1 to 1 in both the x and y directions. For example, the point {-1, -1} in text coordinates represents the bottom left-hand corner of the text element and {1, 1} the top right-hand corner. With the help of the text coordinates, we can place the text element in other ways. For example, [email protected], 83, 4<, 8-1, 0
Here, the vertical middle of the left-hand end of expr is at the point {3, 4}; that is, the text starts from {3, 4}. The following table explains the most frequently used text coordinates:

164

Mathematica Navigator

t is centered below 8x,y<

[email protected],8x,y<,8-1,1
[email protected],8x,y<,80,1
The top left corner of t is at 8x,y<

[email protected],8x,y<,81,1
The top right corner of t is at 8x,y<

[email protected],8x,y<,8-1,0
[email protected],8x,y<,80,0
[email protected],8x,y<,81,0
[email protected],8x,y<,8-1,-1
[email protected],8x,y<,80,-1
t is centered above 8x,y<

[email protected],8x,y<,81,-1
The bottom left corner of t is at 8x,y<

The bottom right corner of t is at 8x,y<

An example:

[email protected]@xD, 8x, 0, 2 p<, PlotRange Ø 8-1.2, 1.2<, Ticks Ø 88p, 2 p<, 8-1, 1<<, Epilog Ø [email protected] ê 2, 1
maximum

p -1

2p

minimum

Note that if a part of a text goes outside the ordinary plot region, that part is not shown in the plot. Without the explicit value of the PlotRange option, this would be the case in our example (even PlotRange Ø All does not help). Enlarging the figure with the mouse may also help to see all Text primitives. Text[expr, {x, y}, {u, v}, {r, s}] Text is rotated to have slope s/r

The following plot shows some slope definitions {r, s}:

[email protected]@"bottom to top: 80,1<", 8-1, 0<, 80, 0<, 80, 1
top to bottom: 80,-1<

bottom to top: 80,1<

left to right: 81,0<

right to left: 8-1,0<

‡ Style of Text

We can adjust the style of text items with Style. It accepts both font directives and font options. Text[Style[expr, dirsAndOpts], {x, y}] Text has the given directives and options

Chapter 6 • Graphics Primitives

165

Font directives: n, Tiny, Small, Medium, Large, Smaller, Larger Bold, Italic, Underlined, Plain Red, LightBlue, GrayLevel[0.3], etc. Font options: FontFamily; examples of values: "Times", "Helvetica", "Courier" FontColor; examples of values: Red, Gray FontTracking; examples of values: "Narrow", "Condensed", "SemiCondensed", "Extended", "Wide" Background; examples of values: LightGray, LightBlue

The default size of text in graphics is 10. The size can be any number such as 9; or Tiny (means size 6), Small (9), Medium (12), or Large (24); or Smaller (8) or Larger (10). This kind of absolute font size does not change if the size of the plot is changed with the mouse. If the size is defined with, for example, Scaled[0.05], then the size of the font is 0.05 times the width of the plot. In addition to the options we have shown previously for Style, we can use many other options, such as LineSpacing, TextAlignment, and Magnification. [email protected]@xD, 8x, 0, 2 p<, PlotRange Ø 8-1.2, 1.4<, Epilog Ø [email protected] ê 2, 1
1.0 0.5

-0.5

1

2

3

4

5

6

-1.0

‡ Coordinates {x, y} A point in the original coordinates of the plot Scaled[{sx, sy}] A point in the scaled coordinates

Thus far, we have defined the positions of graphics primitives with the normal coordinates used in the plot. Another way is to use scaled coordinates that run from 0 to 1 in both directions. An example: [email protected], 8x, 0, 2 p<, Epilog Ø [email protected] ê 2, 1
TextAStyleA"A function with\na minimum and\na maximum", TextAlignment Ø RightE, [email protected], 1
1.0

A function with a minimum and a maximum

0.5

1

2

3

4

5

6

-0.5 -1.0

Here, we told Mathematica that the top right corner of the text is at the point Scaled[{1, 1}], which is at the top right corner of the plot (note that in the text string, \n defines a new line). Using scaled coordinates for primitives may be useful, for example, when the original coordinates vary from figure to figure but we want a primitive at the same position in each figure.

166

Mathematica Navigator

Scaled[{sdx, sdy}, {x, y}] Scaled offset {sdx, sdy} from {x, y} Offset[{adx, ady}, {x, y}] Absolute offset {adx, ady} from {x, y} Offset[{adx, ady}, Scaled[{sx, sy}]] Absolute offset from Scaled[{sx, sy}]

The position of a primitive can also be expressed as an offset from a given point. In this way, we can define a position relative to another position. The offset can be set either in scaled coordinates or in absolute units. The absolute unit is one printer’s point (1/72 inch). We already used Offset in a special way when we considered circles: For this primitive, we can give the radius in absolute units with Offset[{adx, ady}].

6.2.7 Rectangle, Polygon, and Disk ‡ Filled Primitives

Mathematica has three filled primitives: Rectangle, Polygon, and Disk. Rectangle[p] Filled unit square with two opposite corners at p and p + 1 (Rectangle[] means Rectangle[{0,0}]) Rectangle[p1, p2] Filled rectangle with two opposite corners at p1 and p2 Polygon[{p1, …, pn}] Filled polygon with vertices p1, ..., pn Disk[p] Filled disk with center p and radius 1 (Disk[] means Disk[{0,0}]) Disk[p, r] Filled disk with center p and radius r Disk[p, Offset[{r, r}]] Filled disk with center p and radius r/72 inch

Two directives: EdgeForm[styles] (Ÿ6) The styles (color, opacity, thickness, dashing) used for the edges FaceForm[styles] (Ÿ6) The styles (color, opacity) used for the faces (or insides) EdgeForm[] means no edges (this is also the default). FaceForm[] means no face (meaning an empty

inside). Disk is used in the same way as Circle. Note that although we have a primitive corresponding to an unfilled disk, namely Circle, we do not have a primitive corresponding to an unfilled rectangle or unfilled polygon. However, as we will see, the EdgeForm and FaceForm directives enable us to create unfilled primitives. Unfilled rectangles and polygons can also be easily generated with Line: Line[{p1, p2, p3, p4, p1}] Rectangle with vertices p1, ..., p4 Line[{p1, …, pn, p1}] Polygon with vertices p1, ..., pn

Here are simple examples:

[email protected]@80, 0<, 82.5, 1
Next, we use various directives. The style of the edge is defined with EdgeForm. The style of the inside can be defined directly, but FaceForm can also be used. FaceForm[] is needed if we want an empty inside:

Chapter 6 • Graphics Primitives

167

[email protected], [email protected], 0<, 0.8D<, 8Yellow, [email protected], [email protected], 0<, 0.8D<, 8LightGreen, [email protected], Thick, Dashed
In the fourth figure, there are two white disks partly on top of each other. In the last figure, there are two empty disks or, which is the same, two circles. The last figure shows how to get a simple unfilled primitive: Use FaceForm[] and EdgeForm[Black]. Next, we use a yellow filled rectangle with a black edge and a white text on a red background: [email protected], [email protected], Thick
STOP ‡ Histograms and Pie Charts

Toss a dice 20 times and plot the frequencies as a histogram: [email protected]; data = [email protected], 6<, 20D

85, 3, 5, 1, 2, 1, 1, 3, 1, 1, 4, 6, 3, 1, 4, 5, 5, 2, 4, 4< fr = [email protected] êê Sort

881, 6<, 82, 2<, 83, 3<, 84, 4<, 85, 4<, 86, 1<<

[email protected], [email protected]ÒP1T - .4, 0<, 8ÒP1T + .4, ÒP2T
2

3

4

5

6

Plot the frequencies as a pie chart: fr2 = frPAll, 2T

86, 2, 3, 4, 4, 1<

168

Mathematica Navigator

[email protected] = 0, n = [email protected], a = 2 p fr2 ê [email protected]<, [email protected]@[email protected] ê nD, [email protected], [email protected], 0<, 1, 8t, t = t + aPiT
‡ Plotting Data

A useful application of Disk is to plot data. Whereas ListPlot uses black points or disks, with Disk we can get disks with white inside: data = [email protected], [email protected]<, 8i, 0, 40
[email protected]@dataD, White, [email protected], [email protected]Ò, [email protected], 1

20

30

40

Here, we first plotted a line connecting the points. Then we plotted white disks with black edges. These disks hide the lines inside the disks. In Section 6.2.3, p. 159, we used circles and the result was not very good because the lines can be seen inside the circles.

6.2.8 Colors and Raster ‡ Color Schemes

Here are the four basic color schemes: GrayLevel[g] Gray level g between 0 (black) and 1 (white) Hue[h] Color with hue h between 0 and 1 (with maximum saturation and brightness) Hue[h, s, b] Color with hue h, saturation s, and brightness b, each between 0 and 1 RGBColor[r, g, b] Color with specified red r, green g, and blue b components, each between 0 and

1 CMYKColor[c, m, y, k] Color with specified cyan c, magenta m, yellow y, and black k components,

each between 0 and 1 (used in four-color printing) Later, we will study a palette that gives us many additional color schemes. Colors can be modified in the following ways:

Chapter 6 • Graphics Primitives

169

Opacity[o] (Ÿ6) Opacity o (0 means complete transparency, 1 complete opacity) Blend[{col1, col2}, x] (Ÿ6) Blend a fraction 1 | x of col1 and x of col2 Lighter[col] or Lighter[Red, f] (Ÿ6) A lighter color (lightened by a fraction f) Darker[col] or Darker[Red, f] (Ÿ6) A darker color (darkened by a fraction f)

Opacity can be defined with Opacity, but opacity specification can also be added as a last argument to each of the color systems GrayLevel, Hue, RGBColor, and CMYKColor. The default lightening or darkening is 1 ê 3 (Lighter[col, 0] and Darker[col, 0] give col, Lighter[col, 1] gives white, and Darker[col, 1] gives black). For some basic colors, we also have ready-to-use names. Grays: Black, Gray, White Hues: Red, Yellow, Green, Cyan, Blue, Magenta Special colors: Pink, Orange, Purple, Brown Each color, except Black and White, can be preceded by Light (LightRed, etc.) All primitives except Raster can be modified with a color. Here are some disks:

[email protected]@0, 1, 0D, [email protected], 0
>

,

Later, we will mention a palette that helps in choosing a suitable color. ‡ Raster

With Raster we can form raster images. Raster[{{g11, … }, … }] An array of gray cells Raster[{{h11, … }, … }, ColorFunction Ø Hue] An array of hue cells Raster[{{{r11, g11, b11}, … }, … }] (Ÿ6) An array of RGB cells

With a second argument of Raster we can inform the rectangle that the raster image will occupy. Next, we demonstrate the color systems by using Raster. ‡ Gray Level

Gray level 0 corresponds to black and 1 to white (contrary perhaps to what you might expect). Here is a sequence of grays from 0 to 1 in steps of 0.1 (the last rectangle, which is white, is not visible): [email protected]@[email protected], 8g, 0, 1, 1 ê 10
0.

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1.

170

Mathematica Navigator

‡ Hue

When the argument in the hue specification ranges from 0 to 1/6, 2/6, 3/6, 4/6, 5/6, and 1, the color changes from red to yellow, green, cyan, blue, magenta, and back to red. In the following, we have several hues: [email protected]@[email protected], 8g, 0, 1, 1 ê 12
0

1

1

1

1

5

1

7

2

3

5

11

12

6

4

3

12

2

12

3

4

6

12

1

Next, we show a color wheel showing how the hue changes (the wheel is implemented by plotting 300 narrow sectors of a disk): d = p ê 150; [email protected]@Ò ê H2 p - dLD, [email protected], 0<, 1, 8Ò, Ò + d
‡ RGB Color

In the RGB system, we specify the intensity of red, green, and blue. For example, RGBColor[1, 0, 0] is red, RGBColor[0, 1, 0] is green, and RGBColor[0, 0, 1] is blue. This color system corresponds to the one used in color monitors. In the following three tables, we have various RGB colors when the blue component has the value 0, 0.5, and 1. [email protected][email protected]@8r, g, Ò<, 8g, 0, 1, .5<, 8r, 0, 1, .5
:

,

,

>

Indexed and named color schemes may be useful as values of PlotStyle in commands such as Plot or ListPlot or as color directives in Graphics: data = [email protected] - n ê 6L x + 0.4 [email protected], 8n, 1, 6<, 8x, 0, 5, 0.1
[email protected]@[email protected]@n xD, 8n, 1, 3
1.0

:

8

0.5

6 1

2

3

-0.5 -1.0

4

5

6

,

,

4

>

2 10

20

30

40

50

In the first plot, the palette only gives ColorData[16]; we have to add "ColorList" after the index of the color scheme to get a list of colors. In the second plot, we have done similarly. The color definitions in the third plot are directly from the palette. The color schemes of the palette can also be studied and used directly with the ColorData command; see Section 9.3.3, p. 304.

Chapter 6 • Graphics Primitives

173

6.2.9 GraphicsComplex ‡ Building Plots from Primitives

Often in building a plot from primitives, we have a set of points and then we draw various primitives, many of them depending on the same points. Of course, we can use the points as such in the primitives, as in the following: p = [email protected], [email protected]<, 8x, 0., 2 p, p ê 10
[email protected]@pD, [email protected]<, Axes Ø TrueD 1.0 0.5 -0.5 -1.0

1

2

3

4

5

6

However, we have a special command to help build a plot from primitives. GraphicsComplex[{p1, p2, … }, data] (Ÿ6) In the nested list data of directives and primitives,

refer to point pi by i Here, we first give the list of points. Then we can refer to the points simply by their ordinal numbers: Point pi can be referred to by i. This means that the set of all points can be referred to by Range[n], where n is the number of points. Let us now redraw the previous plot: [email protected] = [email protected]@pDD<, [email protected]@p, [email protected], [email protected]
1

2

3

4

5

6

GraphicsComplex is treated like a single primitive in Graphics. The advantage of GraphicsComplex is not very clear from this simple example, but in more complex plots the advantage may become more prominent.

Next, using GraphicsComplex, we redraw a plot we considered in Section 6.2.3, p. 159:

[email protected]@p = 880, 0<, 83, 0<, 83, 1<, 80, 1<<, [email protected], [email protected], [email protected], 3
a

With Normal we get the usual graphics primitives:

[email protected] = 880, 0<, 83, 0<, 83, 1<, 80, 1<<, [email protected], [email protected], 3
Most surface and region plots produce GraphicsComplex:

174

Mathematica Navigator

[email protected]@x yD, 8x, 0, p<, 8y, 0, p>D, 8<< 7 >>
Let us write a program that draws circles with labels and connects some of the circles with arrows. Let the data be as follows: nodes = 880, 2<, 82, 4<, 82, 3<, 82, 2<, 82, 1<, 82, 0<, 84, 3<, 84, 1<<; labels = [email protected]"a", "h"D; arcs = 881, 2<, 81, 3<, 81, 4<, 81, 5<, 81, 6<, 82, 7<, 82, 8<, 83, 7<, 83, 8<, 84, 7<, 84, 8<, 85, 7<, 85, 8<, 86, 7<, 86, 8<<;

We want to draw circles of radius r at nodes, and labels are written inside the circles. The list arcs gives the pairs of node numbers between which arrows are drawn; node numbers are 1, 2, and so on in the order they are given in nodes. First, define that rn contains the ordinal numbers of the nodes. Then generate the circles, labels, and arrows: rn = [email protected]@nodesDD 81, 2, 3, 4, 5, 6, 7, 8<

[email protected]Ò, rD & êü rn êê Short

[email protected], rD, á6à, [email protected], rD<

[email protected], 8labels, rn
[email protected], 1D, [email protected], 2D, á5à, [email protected], 8D< [email protected]Ò, rD & êü arcs êê Short

[email protected], 2<, rD, á13à, [email protected], 8<, rD<

Thus, a program could be as follows: [email protected]_, labels_, arcs_, r_, opts___D := [email protected] = [email protected]@nodesDD<, [email protected]@nodes, [email protected]Ò, rD & êü rn, [email protected], 8labels, rn
c

a

g

d

e

h

f

We also have the built-in command GraphPlot that we consider in Section 8.5, p. 267: arcs2 = 81 Ø 2, 1 Ø 3, 1 Ø 4, 1 Ø 5, 1 Ø 6, 2 Ø 7, 2 Ø 8, 3 Ø 7, 3 Ø 8, 4 Ø 7, 4 Ø 8, 5 Ø 7, 5 Ø 8, 6 Ø 7, 6 Ø 8<;

Chapter 6 • Graphics Primitives

175

[email protected], VertexCoordinateRules Ø nodes, VertexLabeling Ø True, DirectedEdges Ø TrueD 2

3

1

7

4

5

8

6

6.2.10 Inset Previously, we have considered primitives such as Point, Line, and Text. With Inset, we can create, from an arbitrary graphics, an object that can be used like a primitive. Inset[gr] (Ÿ6) Inset graphics gr at the center of the enclosing graphics Inset[gr, pos] Put the center of gr at pos of the enclosing graphics Inset[gr, pos, opos] Put point opos of gr at pos of the enclosing graphics Inset[gr, pos, opos, size] Define the size of gr in units of the enclosing graphics Inset[gr, pos, opos, size, dir] Define the direction of gr

Although here we use Inset for a graphics gr, we can inset any expression. In the positions, we can also use x-positions Automatic, Left, Center, Right, and Axis and y-positions Automatic, Bottom, Center, Top, Axes, or Baseline. With the Alignment option (Left, Center, or Right) we can define how to align the contents of the inset.

In the following figures, we use the plot of sinHxL as a primitive: p = [email protected]@xD, 8x, 0, 2 p
p1 = [email protected]@81, 0<, 1D, [email protected]<, ImageSize Ø 90D; p2 = [email protected]@81, 0<, 1D, [email protected], 81, 0.5
1

2

3

4

5

"D

1

2

3

4

5

1.0 0.5 0.0 -0.5 123456 -1.0

10..050 23456 0..5 1 --01.0

176

Mathematica Navigator

• In the first plot, the center of the plot of sinHxL is at the center of the enclosing graphics. • In the second plot, the center of the plot of sinHxL is at the point H1, 0.5L of the enclosing graphics. • In the third plot, the point H0, -1L of the plot of sinHxL is at the point H1, 0L of the enclosing graphics and the size of the plot of sinHxL is 1.2 units in the enclosing graphics. • In the fourth plot, the slope of the x axis of the plot of sinHxL is 1 ê 2. Next, we use Inset in an Epilog option:

[email protected]@xD, 8x, 0, 2 p<, Epilog Ø [email protected]@[email protected], 8x, 0, 2 p
"The graph of\nthe sine function", TextAlignment Ø RightEE, 82 p, 1<, 81, 1
1.0

:

1.0 1.0 0.5

0.5 1

2

-0.5 -1.0 3

1.0 The graph of the sine function

0.5 1 2 3 4 5 6 4

5

6

,

1

2

3

4

5

6

The graph of the sine function

0.5

,

1

-0.5

-0.5

-0.5

-1.0

-1.0

-1.0

2

3

4

5

6

>

• In the first plot, we inset the plot of cosHxL with size 3.5 so that its right top point is at the point H2 p, 1L of the enclosing graphics. • In the second plot, we inset a text with right alignment. • In the third plot, we use, instead of Inset, the Text primitive. Now we have to define the line breaks with \n and use Style to define the alignment. GraphicsGroup[{gr1, gr2, … }] (Ÿ6) Represents a collection of graphics objects grouped together

Grouping of graphics objects may be useful in interactive selection of objects. Grouping can also be done by using the menu command Graphics @ Operations @ Group; see Section 5.1.3, p. 131.

6.2.11 3D Primitives and Directives ‡ The Structure of 3D Graphics

Thus far, we have considered 2D graphics primitives and directives. Similarly, we have 3D primitives and directives. As for 2D graphics, the importance of the 3D primitives and directives derives from three facts: •Mathematica uses the primitives and directives in the construction of all plots. •We can construct a plot directly from the primitives and directives. •The directives can be used to modify plots with options. The construction of 3D graphics from primitives is done with Graphics3D: Graphics3D[{directives and primitives}, options] Create and show a graphics object from

directives and primitives, using some options

Chapter 6 • Graphics Primitives

177

Graphics3D has mostly the same options as Plot3D, but the default values of Axes and BoxRatios are False and Automatic, whereas the default values for Plot3D are True and {1, 1, 0.4}.

Here are two examples. The second example shows that we can use GraphicsComplex (see Section 6.2.9, p. 173) in the same way as for 2D graphics:

[email protected]@80, 0, 0<, 81, 1, 1
:

,

>

‡ 3D Graphics Primitives

The following are all the 3D graphics primitives. With p, p1, p2, and pn, we denote a point that consists of the x, y, and z coordinates; an example is {1, 4, 3}. Point[p] Point at p Point[{p1, …, pn}] Points at p1, …, pn Line[{p1, …, pn}] Line through points p1, …, pn Text[expr, p] Text expr centered at p Text[expr, p, {u, v}] Text expr placed so that the point {u, v}, expressed in text coordinates, of expr is at the point p Cuboid[p] Cube with opposite corners p and p + 1 (Cuboid[] means Cuboid[{0, 0, 0}]) Cuboid[p1, p2] Rectangular parallelepiped with opposite corners p1 and p2 Polygon[{p1, …, pn}] Polygon with vertices p1, …, pn Sphere[p] (Ÿ6) Sphere of radius 1 centered at p (Sphere[] means Sphere[{0, 0, 0}]) Sphere[p, r] Sphere of radius r centered at p Cylinder[{p1, p2}] (Ÿ6) Filled cylinder of radius 1 around the line from p1 to p2 (Cylinder[]

means Cylinder[{{0, 0, -1}, {0, 0, 1}}]) Cylinder[{p1, p2}, r] Filled cylinder of radius r around the line from p1 to p2

For Text, note that the point p at which the text is placed is a 3D point, but the text coordinates {u, v} are 2D. The faces of a Cuboid are parallel to the axes. To get other cuboids, use Rotate. To get

ellipsoids, apply Scale to a Sphere. With Graphics3D, we can use GraphicsComplex, GraphicsGroup, and Inset as with Graphics (see Sections 6.2.9, p. 173, and 6.2.10, p. 175). Note that the 3D primitives cannot be used in the Prolog and Epilog options. In these options, we can only use 2D primitives.

178

Mathematica Navigator

‡ 3D Graphics Directives

For 3D primitives, we have all of the directives of point size, thickness, dashing, and color as we do for 2D primitives: PointSize[d], AbsolutePointSize[d] Thickness[d], AbsoluteThickness[d] Dashing[{d1, d2, … }], AbsoluteDashing[{d1, d2 ,… }] GrayLevel[g], Hue[h], RGBColor[r, g, b], CMYKColor[c, m, y, k]

In addition, the style of 3D polygons can be adjusted with the following directives: EdgeForm[styles] Styles of the edges (EdgeForm[] means no edges) FaceForm[styles] Styles of both front and back faces (FaceForm[] means no faces) FaceForm[front styles, back styles] Styles of front and back faces Opacity[o] (Ÿ6) The opacity Specularity[col, n] (Ÿ6) The specularity (a color and a specular exponent) Glow[col] (Ÿ6) The glow

In FaceForm, the front face of a polygon is defined to be the one for which the corners, as you specify them, are in counterclockwise order. Here are some examples of how the style of polygons can be adjusted: [email protected], ImageSize Ø 90D;

[email protected]@DD, [email protected]@0.4D, [email protected]
:

,

,

>

,

‡ Polyhedrons

With PolyhedronData, we can get information about many polyhedrons. This command is considered in Section 9.3.1, p. 300. Here are images of some well-known polyhedrons:

[email protected]@Ò, "Image"D, Boxed Ø False, ImageSize Ø 70D & êü 8"Tetrahedron", "Cube", "Octahedron", "Dodecahedron", "Icosahedron"<

:

,

,

,

,

>

7 Graphics Options Introduction 180 7.1 Introduction to Options 180 7.1.1 Using Options 180 Show, SetOptions, Options, AbsoluteOptions 7.1.2 Summary 184 Directive 7.2 Options for Form, Ranges, and Fonts 189 7.2.1 Form and Size 189 AspectRatio, ImageSize 7.2.2 Plot Range 190 PlotRange, PlotRangeClipping 7.2.3 Margins and Background 191 PlotRegion, ImageMargins, Background, ImagePadding, etc. 7.2.4 Fonts 192 BaseStyle, FontFamily, FontColor, LabelStyle, Style, FormatType, etc. 7.2.5 Miscellaneous Options 195 BaselinePosition, AlignmentPoint, ContentSelectable, etc. 7.3 Options for Axes, Frames, and Primitives 195 7.3.1 Plot Label 195 PlotLabel 7.3.2 Axes and Ticks 196 Axes, AxesOrigin, AxesLabel, AxesStyle, Ticks, TicksStyle 7.3.3 Frame and Frame Ticks 198 Frame, FrameLabel, RotateLabel, FrameStyle, FrameTicks, etc. 7.3.4 Grid Lines 199 GridLines, GridLinesStyle 7.3.5 Hierarchy of Styles 200 BaseStyle, LabelStyle, AxesStyle, FrameStyle, TicksStyle, etc. 7.3.6 Primitives 201 Prolog, Epilog, Graphics 7.4 Options for the Curve 203 7.4.1 Plot Style 203 PlotStyle, ClippingStyle 7.4.2 Color Function 204 ColorFunction, ColorFunctionScaling 7.4.3 Filling 204 Filling, FillingStyle 7.4.4 Mesh Points 205 Mesh, MeshFunctions, MeshStyle, MeshShading 7.4.5 Exclusions and Region Function 206 Exclusions, ExclusionsStyle, RegionFunction 7.4.6 Plotting Algorithm 207 PlotPoints, MaxRecursion, WorkingPrecision, Evaluated, etc. 7.4.7 Legends 208 PlotLegend, LegendPosition, LegendSize, LegendShadow, ShowLegend, etc. 7.5 Options for Surface Plots 210 7.5.1 Summary 210 7.5.2 Global Options 215 BoxRatios, PlotRange, SphericalRegion, ViewPoint, Lighting, etc. 7.5.3 Local Options 219 Axes, AxesEdge, AxesLabel, Ticks, Boxed, FaceGrids, Epilog, etc. 7.5.4 Options for the Surface 222 ColorFunction, Filling, Mesh, Exclusions, RegionFunction, etc. 7.6 Options for Contour and Density Plots 226 7.6.1 Special Options 226 Contours, ContourLines, ContourLabels, ContourShading, etc.

180

Mathematica Navigator

Introduction Isaac Newton, it seems, was one of the original absentminded mathematicians. He once cut a hole in the bottom of the door of an outhouse to allow his favorite cat easy access. When the cat had kittens, he added a small hole next to the big one. We shall now explore in detail all the options of the main 2D plotting commands Plot, ParametricÖ Plot, and Graphics and of the main 3D commands Plot3D, ParametricPlot3D, Graphics3D, ContourPlot, and DensityPlot. In Sections 7.1.2 and 7.5.1, we present summaries of the options. The options are classified into global options, which modify the plot as a whole, local options, which modify separate components of the figure, and options for the curve or surface. The varying importance of the options is also shown. Many options relating to styles such as PlotStyle, BaseStyle, and FrameStyle use graphics directives, and the options Prolog and Epilog also use graphics primitives. You may want to study them in Chapter 6.

7.1 Introduction to Options 7.1.1 Using Options ‡ Four Ways to Adjust Options

In Section 5.1.1, p. 118, we explained how options can be used to modify a plot. Here, we summarize four methods of using options. We use Plot as an example of a plotting command. (a) Setting options in Plot: Plot[expr, {x, a, b}, opt1 Ø val1, opt2 Ø val2, …]

(b) Setting options in Show: p = Plot[expr, {x, a, b}] Show[p, opt1 Ø val1, opt2 Ø val2, …]

(c) Giving a name to the options: opts = Sequence[opt1 Ø val1, opt2 Ø val2, …] Plot[expr, {x, a, b}, Evaluate[opts]]

(d) Setting options with SetOptions: SetOptions[Plot, opt1 Ø val1, opt2 Ø val2, …] Plot[expr, {x, a, b}]

(a) The first method may be the most convenient in a notebook environment (as in Windows and on a Macintosh). You can first plot the function without any options. If the result is not satisfactory, add an option or several options to the original plotting command and then execute the command anew. Continue adding and modifying the options and executing the plotting command until you are satisfied with the result. (b) The second method has a certain advantage. Indeed, Show does not execute the plotting command anew; only the appearance of the figure is changed. Thus, if the plotting command is time-consuming, it is better to use Show to avoid executing the plotting command anew every time.

Chapter 7 • Graphics Options

181

(c) The third method may be useful if you use the same options ( opts) for several plots: Write the options once and use the name of the set of options in the subsequent plots. (d) The fourth method is useful if, during a session, you continuously use certain values for some options. Before using this method, it may be useful to look at the default values with Options[Plot] for the case in which you want to return to the default values. The default values can then be set with another SetOptions command. ‡ Notes about Show

If you combine two or more figures with Show, you should be aware of the fact that if the figures have different values for the same option, then Show takes the value given in the first figure; the values given in later figures for this option are disregarded (see Section 5.1.2, p. 125). Also, with Show we can adjust most of the options but not all of them. Indeed, with Show we can only adjust the options of Graphics. For example, Plot has the following options that Graphics does not have: ClippingStyle,

ColorFunction,

ColorFunctionScaling,

EvaluationMonitor,

Exclusions,

ExclusionsStyle, Filling, FillingStyle, MaxRecursion, Mesh, MeshFunctions, MeshShading, MeshStyle, PerformanceGoal, PlotPoints, PlotStyle, RegionFunction, WorkingPrecision.

These options control the sampling algorithm and the style of the curve. Thus, the options mentioned cannot be adjusted with Show. Note especially that PlotStyle cannot be used with Show. ‡ Information about Options Options[comm] Give the options and their default values of a command comm Options[comm, opt] Give the default value of an option opt of a command comm AbsoluteOptions[p] Give the detailed values of the options used in a plot p, even if a value is Automatic or All AbsoluteOptions[p, opt] Give the detailed value of an option opt used in a plot p

Note that for a plot produced by Plot, the values of the special options mentioned previously cannot be asked. Here are all the 55 options and their default values for Plot: [email protected]@PlotD, 7D :AlignmentPoint Ø Center, AspectRatio Ø

1 , Axes Ø True, AxesLabel Ø None, GoldenRatio AxesOrigin Ø Automatic, AxesStyle Ø 8<, Background Ø None, BaselinePosition Ø Automatic, BaseStyle Ø 8<, ClippingStyle Ø None, ColorFunction Ø Automatic, ColorFunctionScaling Ø True, ColorOutput Ø Automatic, ContentSelectable Ø Automatic, DisplayFunction ß $DisplayFunction, Epilog Ø 8<, Evaluated Ø Automatic, EvaluationMonitor Ø None, Exclusions Ø Automatic, ExclusionsStyle Ø None, Filling Ø None, FillingStyle Ø Automatic, FormatType ß TraditionalForm, Frame Ø False, FrameLabel Ø None, FrameStyle Ø 8<, FrameTicks Ø Automatic, FrameTicksStyle Ø 8<, GridLines Ø None, GridLinesStyle Ø 8<, ImageMargins Ø 0., ImagePadding Ø All, ImageSize Ø Automatic, LabelStyle Ø 8<, MaxRecursion Ø Automatic, Mesh Ø None, MeshFunctions Ø 8Ò1 &<, MeshShading Ø None, MeshStyle Ø Automatic, Method Ø Automatic, PerformanceGoal ß $PerformanceGoal, PlotLabel Ø None, PlotPoints Ø Automatic, PlotRange Ø 8Full, Automatic<, PlotRangeClipping Ø True, PlotRangePadding Ø Automatic, PlotRegion Ø Automatic, PlotStyle Ø Automatic, PreserveImageOptions Ø Automatic, Prolog Ø 8<, RegionFunction Ø HTrue &L, RotateLabel Ø True, Ticks Ø Automatic, TicksStyle Ø 8<, WorkingPrecision Ø MachinePrecision>

The default value of a certain option or a list of options can also be displayed: 8PlotRange Ø 8Full, Automatic<<

[email protected], PlotRangeD

182

Mathematica Navigator

Remember also that we can ask for information about an option by typing, for example, ?PlotRange or using the Documentation Center (see Sections 1.4.2, p. 17, and 1.4.3, p. 20). Some common values of options are as follows. Most default values of the options of Plot are Automatic. This value means that there is a special value chosen by Plot according to certain rules.

Some options, such as AxesLabel, have the value None, meaning that the plot does not have the corresponding components. Some options, such as Frame, have the value True or False, which tells whether or not something is present. PlotRange can have the value All, meaning that the whole plot is shown. We can also ask for the options of a given plot: p = [email protected]@xD, 8x, 0, 2 p
2

3

4

5

6

-0.5 -1.0

8AxesStyle Ø 88Gray[email protected], [email protected]<, [email protected], [email protected]<<< [email protected], AxesStyleD

‡ Comparing Options

We can easily compare the options of various plotting commands. For example, LogPlot has exactly the same options and default values as LogLinearPlot: [email protected] ã [email protected] True

The options of Plot and Graphics have some differences: c = [email protected]; g = [email protected]; [email protected]@c, gD, 7D

8AlignmentPoint Ø Center, AxesLabel Ø None, AxesOrigin Ø Automatic, AxesStyle Ø 8<, Background Ø None, BaselinePosition Ø Automatic, BaseStyle Ø 8<, ColorOutput Ø Automatic, ContentSelectable Ø Automatic, Epilog Ø 8<, Frame Ø False, FrameLabel Ø None, FrameStyle Ø 8<, FrameTicks Ø Automatic, FrameTicksStyle Ø 8<, GridLines Ø None, GridLinesStyle Ø 8<, ImageMargins Ø 0., ImagePadding Ø All, ImageSize Ø Automatic, LabelStyle Ø 8<, Method Ø Automatic, PlotLabel Ø None, PlotRangePadding Ø Automatic, PlotRegion Ø Automatic, PreserveImageOptions Ø Automatic, Prolog Ø 8<, RotateLabel Ø True, Ticks Ø Automatic, TicksStyle Ø 8<, DisplayFunction ß $DisplayFunction, FormatType ß TraditionalForm<

[email protected]@c, gD, 7D :AspectRatio Ø

1 , Axes Ø True, ClippingStyle Ø None, ColorFunction Ø Automatic, GoldenRatio ColorFunctionScaling Ø True, Evaluated Ø Automatic, EvaluationMonitor Ø None, Exclusions Ø Automatic, ExclusionsStyle Ø None, Filling Ø None, FillingStyle Ø Automatic, MaxRecursion Ø Automatic, Mesh Ø None, MeshFunctions Ø 8Ò1 &<, MeshShading Ø None, MeshStyle Ø Automatic, PlotPoints Ø Automatic, PlotRange Ø 8Full, Automatic<, PlotRangeClipping Ø True, PlotStyle Ø Automatic,

RegionFunction Ø HTrue &L, WorkingPrecision Ø MachinePrecision, PerformanceGoal ß $PerformanceGoal>

[email protected]@g, cD, 7D

8AspectRatio Ø Automatic, Axes Ø False, PlotRange Ø All, PlotRangeClipping Ø False<

Complement[c, g] gives the elements of c that are not in g. Thus, the default values of AspectRatio, Axes, PlotRange, and PlotRangeClipping are different for the two plotting commands, and Graphics

does not have the special options of Plot we mentioned previously.

Chapter 7 • Graphics Options

183

The options of Plot and ParametricPlot also have some differences: c = [email protected]; p = [email protected]; [email protected], pD :AspectRatio Ø

1 , ClippingStyle Ø None, GoldenRatio Filling Ø None, FillingStyle Ø Automatic, Frame Ø False,

Mesh Ø None, MeshFunctions Ø 8Ò1 &<, PlotRange Ø 8Full, Automatic<>

8AspectRatio Ø Automatic, BoundaryStyle Ø Automatic, Frame Ø Automatic, Mesh Ø Automatic, MeshFunctions Ø Automatic, PlotRange Ø Automatic< [email protected], cD

Thus, the default values of AspectRatio, Frame, Mesh, MeshFunctions, and PlotRange are different, and ParametricPlot does not have the options ClippingStyle, Filling, and FillingStyle. ‡ Example

With the help of options we can get interesting results, such as the following. This plot is overdone, but our aim is simply to show what can be done with options. [email protected]@xD, 8x, 0, 2 p<, PlotRange Ø 88-0.7, 2 p + 0.7<, 8-1.6, 1.6<<, PlotRegion Ø 88-0.05, 1<, 80.04, 0.94<<, ImageSize Ø 8280, 190<, Background Ø Black, BaseStyle Ø 89, White, FontFamily Ø "Helvetica"<, PlotStyle Ø [email protected], ThickD, PlotLabel Ø [email protected]"An interesting wave", Bold, 12D, Frame Ø True, FrameLabel Ø [email protected], WhiteD, [email protected]@xD, WhiteD<, RotateLabel Ø False, FrameStyle Ø [email protected], Thick, BoldD, FrameTicks Ø 880, 8p ê 2, "pê2"<, p, 83 p ê 2, "3pê2"<, 2 p<, 8-1, 0, 1<, None, None<, FrameTicksStyle Ø [email protected], ThinD, Epilog Ø 8 [email protected]@"Maximum point", Bold, 7D, 8p ê 2, 1<, 8-1, -1.3
An interesting wave Maximum point

1 sinHx L

Point of inflection

0

-1

Minimum point

0

pê2

p

x

3pê2

2p

184

Mathematica Navigator

7.1.2 Summary ‡ Introduction

Here, we list all the options of Plot (see Section 5.1.1, p. 116), ParametricPlot (see Section 5.2.1, p. 132), and Graphics (see Section 6.1.1, p. 153), with short descriptions and some common values. The default value of an option is mentioned first, and after that we mention either all other possible values or some examples of other values (the examples are simple; more advanced forms may exist). The options are divided into three groups: • Global options: These are options to modify global aspects of the plot~that is, to adjust how the plot looks in general. This means, for example, adjusting the form, size, plot range, various margins, or fonts. • Local options: These are options to modify local components of a plot such as plot label, axes, ticks, frame, grid lines, or add-ons. • Options for the curve: These are options to modify the curve produced by Plot or ParametricPlot. This means, for example, adjusting the style, filling, mesh, or exclusions or controlling the plotting algorithm. All of the options in the first two groups are common to all three plotting commands mentioned. However, options in the third group are applicable only with Plot or ParametricPlot. Options and their default values applicable only to certain commands are expressed in the lists in this section by a superscript after the option name or value: c

: applicable to Plot (shorthand for curve) : applicable to ParametricPlot (shorthand for parametric) g : applicable to Graphics (shorthand for graphics)

p

For example, PlotStyle c p means that this option applies to Plot and ParametricPlot but not to g means that the default value of the option in question (Axes) is False for Graphics. Graphics, and False

Three options assumed to be the most important are marked with two asterisks ( **). Nine options assumed to be less important are marked with one asterisk (*). A single parenthesis indicates options that most of us will seldom need. The remaining options, without any special markings, may sometimes be useful. Of course, the given classification of the options according to importance reflects my personal impression. You may well have a different classification.

Chapter 7 • Graphics Options

185

‡ Global Options

The following options can be used to adjust some global aspects of a plot. Options for form and size: ** AspectRatio Ratio of height to width of the plotting rectangle; examples of values: 1/GoldenRatio c , Automatic

gp

, Full, 0.4

ImageSize The absolute size (in printer’s points) of the plot; examples of values: Automatic, Full, All, width, {width, height}, {maxsize}, {{maxwidth}, {maxheight}}

Options for plot range: ** PlotRange Ranges for x and y in the plot; examples of values: Automatic

p

c

{ymin, Automatic}

{Full, Automatic}

{ymin, All}

{{xmin, xmax}, Automatic}

Full

{All, ymax}

{Full, {ymin, Automatic}}

5

{ymin, ymax}

{{xmin, xmax}, {ymin, ymax}}

All

g

(PlotRangeClipping (Ÿ6) Whether graphics objects should be clipped at the edge of the region defined by PlotRange or should be allowed to extend to the selection rectangle; possible values: True c p , False g ) Options for margins: PlotRegion Specifies margins around the plot inside the selection rectangle; examples of values: Automatic (means {{0, 1}, {0, 1}}), {{xmin, xmax}, {ymin, ymax}} (ImageMargins Specifies margins (in printer’s points) outside the selection rectangle; examples of values: 0, Automatic, 15, {{left, right}, {bottom, top}}) Background Color of the background; examples of values: None, LightGray (ImagePadding (Ÿ6) Extra space (in printer’s points) for objects such as thick lines and tick and axes labels; examples of values: All, None, 15, {{left, right}, {bottom, top}}) (PlotRangePadding (Ÿ6) How much farther axes etc. should extend beyond the range of coordinates specified by PlotRange; examples of values: Automatic, None, {0.2, 0.5})

Options for fonts and formatting: * BaseStyle (Ÿ6) Style of all texts; examples of values: {}, {9, "Bold", FontFamily Ø "Arial"} LabelStyle (Ÿ6) Style of all labels; examples of values: {}, {9, "Bold", FontFamily Ø "Arial"} (FormatType Format type of text used in a plot; examples of values: TraditionalForm, StandardForm, InputForm, OutputForm) Miscellaneous options: (BaselinePosition (Ÿ6) Where the baseline of a plot should be if the plot is combined with other plots or text; examples of values: Automatic, Axis, Bottom, Top, Center, Baseline) (AlignmentPoint (Ÿ6) How objects should by default be aligned when they appear in Inset; default value: Center) (ContentSelectable (Ÿ6) Whether and how content of a plot should be selectable; possible values: Automatic (double-click allows content selection), True (single clicks immediately select content objects), False (content objects cannot be selected)) (PreserveImageOptions (Ÿ6) Whether the size and margins of a plot should remain the same if the plotting command is executed anew; examples of values: Automatic (the properties should remain the same if not explicitly otherwise stated), True (the properties should remain the same), False (the previous properties are ignored)) (DisplayFunction Function to apply to a graphic; default value: $DisplayFunction)

186

Mathematica Navigator

‡ Local Options

The following options can be used to adjust some local components of a plot. An option for plot label: PlotLabel Label of the plot; examples of values: None, Sin[x/2], "Function g(x)"

Options for axes and ticks: * Axes Whether to draw the axes; examples of values: True c p , False g , {True, False} * AxesOrigin Point where the axes cross; examples of values: Automatic, {0, 0} AxesLabel Labels for the axes; examples of values: None, y, {x, None}, {x, y} (AxesStyle Style of the axes, axes labels, tick marks, and tick labels; examples of values: {}, Thick, Blue, Arrowheads[0.07], Directive[Thick, Blue, 12, Italic] ** Ticks Tick on the axes; simple examples of values: Automatic, None, {{p, 2p}, Automatic}, {Automatic, {-1, 0, 1}}, {{p, 2p}, {-1, 0, 1}} TicksStyle (Ÿ6) Style of tick marks and tick labels; examples of values: {}, Blue, Directive[Thick, Blue, 12]

Options for frame and frame ticks: * Frame Whether to draw a frame; examples of values: False, True, {True, True, False, False} * FrameLabel Labels for the frame; examples of values: None, {x, y}, {"bottom", "left", "top", "right"} * RotateLabel Whether to rotate the labels for the vertical edges; possible values: True, False FrameStyle Style of the frame, frame labels, frame tick marks, and frame tick labels; examples of

values: Automatic, Blue, Directive[Thick, Red, 12, Italic] * FrameTicks Frame tick marks on the frame; simple examples of values: Automatic, None, All (on

all edges), {{0, p, 2p}, {-1, 1}, None, None} FrameTicksStyle (Ÿ6) Style of frame tick marks and frame tick labels; examples of values: {}, Red, Directive[Thick, Red, 12, Bold]

Options for grid lines: GridLines How the grid lines are drawn; simple examples of values: None, Automatic, {None, Automatic}, {None, {-1,0,1}}, {{0,1,2}, {-1,0,1}} (GridLinesStyle (Ÿ6) Style of the grid lines; examples of values: {}, Dashed, Directive[LightGray, Dashed]) Options for primitives: (Prolog Graphics primitives to be plotted before the main plot; examples of values: {}, {Red, PointSize[Medium], Point[{3, 2}]}) * Epilog Graphics primitives to be plotted after the main plot; examples of values: {}, {Red, PointSize[Medium], Point[{3, 2}]}

Chapter 7 • Graphics Options

187

‡ Options for the Curve

With Plot and ParametricPlot, the following options can be used to adjust the curve to be plotted. Options for plot style: * PlotStyle c p Style(s) of the curve(s); examples of values: Automatic, Thickness[Medium], Directive[Thick, Red, Dashed]

(ClippingStyle c (Ÿ6) How to indicate clipped parts that fall outside of the plot range; examples of values: None, Automatic, Red, {Blue, Red}) Options for color function: (ColorFunction c p (Ÿ6) Function that determines the color of the curve; examples of values: Automatic, (Hue[#2] &), (RGBColor[#2, 0, 1 - #2] &), "Rainbow") (ColorFunctionScaling c p (Ÿ6) Whether arguments to a color function should be scaled to lie between 0 and 1; examples of values: True, False) Options for filling: c (Ÿ6) Type of filling to use; examples of values: None, Axis, Bottom, Top, 0.3, True (FillingStyle c (Ÿ6) Style of filling; examples of values: Automatic, Red, {Blue, Red} (different style for negative and positive values), Directive[Opacity[0.3], Blue]) Filling

Options for mesh: Mesh c p How many mesh points should be drawn; examples of values: None c , Automatic p , 10, Full, All, {{0}} MeshFunctions c p (Ÿ6) How to determine the placement of the mesh points; examples of values: {#1 &} c , Automatic p , {#2 &} MeshStyle c p The style of mesh points; examples of values: Automatic, PointSize[Small], Directive[Red, PointSize[Medium]]

(MeshShading Blue})

cp

(Ÿ6) How to shade regions between mesh points; examples of values: None, {Red,

Options for exclusions: Exclusions c p (Ÿ6) The x points that are excluded in plotting; examples of values: Automatic, None, {p/2, 3 p/2}, {Cos[x] ã 0} ExclusionsStyle c p (Ÿ6) What to draw at excluded points; examples of values: None, Directive[Blue, Dashed], {None, Directive[Red, PointSize[Medium]]} (RegionFunction c p (Ÿ6) Specifies the region to include in the plot drawn; examples of values: (True &), (Abs[#2] > 0.7&)) Options for plotting algorithm: PlotPoints c p Number of initial sampling points; examples of values: Automatic, 100 MaxRecursion c p (Ÿ6) The maximum number of recursive subdivisions allowed; examples of values: Automatic, 8 WorkingPrecision c p (Ÿ6) The precision used in computations; examples of values: MachinePrecision, 20 (Evaluated c p (Ÿ6) Whether the expression to be plotted is evaluated before the expression is sampled; possible values: Automatic, True, False) (PerformanceGoal c p (Ÿ6) What aspect of performance to try to optimize; examples of values: $PerformanceGoal, "Quality", "Speed") (EvaluationMonitor c p (Ÿ6) Expression to evaluate at every function evaluation; examples of values: None, Sow[{x, Sin[x]}])

188

Mathematica Navigator

In various style options we can use graphics primitives such as Point, Line, and Text and graphics directives such as AbsolutePointSize, Thick, Dashed, Gray, or Red. These are explained in Chapter 6. All of the options are explained in detail in the remaining sections of this chapter, after we have considered the combination of various styles. Note that in the PlotLegends` package we have options for legends. ‡ Combining Styles

The styles of various components of a plot can be defined with several options: PlotStyle, ClippingStyle, FillingStyle, MeshStyle, ExclusionsStyle, LabelStyle, AxesStyle, TicksStyle, FrameStyle, FrameTicksStyle, and GridLinesStyle. As an example, consider PlotStyle: [email protected]@[email protected], [email protected]<, 8x, 0, 2 p<, PlotStyle Ø ThickD, [email protected]@xD, [email protected]<, 8x, 0, 2 p<, PlotStyle Ø 8Thick, Blue
1.0 0.5 1 2 3 4 5 6

1.0 0.5 1 2 3 4 5 6

-0.5 -1.0

1.0 0.5 1 2 3 4 5 6

-0.5 -1.0

-0.5 -1.0

1 2 3 4 5 6

In these four plots, examine the use of braces in the value of PlotStyle. In the first plot, we have only one directive, Thick, and it is applied for both curves. In the second plot, we have two directives inside single braces, and now the first directive, Thick, defines the style of the first curve and the second directive, Blue, the style of the second curve. If we want both curves to be blue and thick, we have to use double braces, as is done in the third plot. If we want unique styles for both curves, we use a nested list for the directives, as can be seen in the fourth plot. It may be difficult to remember when to use single braces and when to use double braces. The use of Directive may then be helpful. Directive[dir1, dir2, … ] (Ÿ6) Represents a single graphics directive composed of the given

directives Thus, with Directive we can collect together several directives and use the collection like a single directive. The third and fourth plots can now be written as follows: [email protected]@xD, [email protected]<, 8x, 0, 2 p<, PlotStyle Ø [email protected], ThickDD, [email protected]@xD, [email protected]<, 8x, 0, 2 p<, PlotStyle Ø [email protected], ThickD, [email protected], ThickD
:

1.0

1.0

0.5

0.5 1

2

3

4

5

6

,

1

-0.5

-0.5

-1.0

-1.0

2

3

4

5

6

>

As can be seen, with Directive we need single braces only if we define different styles for each of several curves, and double braces are not needed at all. As another example, consider defining the style of a frame:

Chapter 7 • Graphics Options

189

[email protected]@xD, 8x, 0, 2 p<, Frame Ø True, FrameStyle Ø 88Thick, Blue<, 8Thick, Blue<, 8Thick, Blue<, 8Thick, Blue<
:

1.0

0.5

0.5

0.0

>

0.0

,

-0.5

-0.5

-1.0

-1.0 0

1

2

3

4

5

6

0

1

2

3

4

5

6

In the first plot, we had to separately define the style of each edge of the frame, whereas in the second plot the use of Directive enables us to define the style only once. We will use Directive in this book to collect several directives together, but if you are comfortable with the braces, they can often also be used.

7.2 Options for Form, Ranges, and Fonts 7.2.1 Form and Size ** AspectRatio Ratio of height to width of the plotting rectangle; examples of values: 1/GoldenRatio c , Automatic

gp

, Full, 0.4

The default value 1/GoldenRatio = 0.618 of AspectRatio for Plot gives an aesthetically pleasing form. The default value Automatic of AspectRatio for Graphics and ParametricPlot sets one unit on the x axis to have the same length as one unit on the y axis. The aspect ratio can be any positive real number. The value Full means that the graphic should be stretched so as to fill out its enclosing region in Grid or related construct. Next, we plot a circle with each of the three commands. The curve produced by Plot looks like an ellipse because of the aspect ratio 0.618: [email protected]@[email protected] - x ^ 2D, [email protected] - x ^ 2D<, 8x, -1, 1
0.5

1.0

1.0

1.0

0.5

0.5

-1.0 -0.5 -0.5 -1.0

0.5

1.0

-1.0 -0.5 -0.5

0.5

1.0

-1.0

ImageSize The absolute size (in printer’s points) of the plot; examples of values: Automatic, Full, All, width, {width, height}, {maxsize}, {{maxwidth}, {maxheight}}

The size of the plot is easy to change with the mouse, but we can also use the ImageSize option. It determines the absolute size of the plot in units of printer’s points (1 ê 72 inch). One number as the value of the option defines the width, and a list of two numbers determines both the width and the height. Note that if both the width and the height are specified, the plot fills this area only if the aspect ratio is exactly height/width. The default size can be changed with the Option Inspector.

190

Mathematica Navigator

The value Full for ImageSize means that on the screen, the size of the graphic is automatically adjusted to fit the window and, when printed, the graphic has the full width of the content area of the page. The aspect ratio of a plot is kept fixed when resizing, unless AspectRatio is Full. The value of ImageSize can also be Tiny, Small, Medium, or Large.

7.2.2 Plot Range ** PlotRange Ranges for x and y in the plot; examples of values: Automatic

p

c

{ymin, Automatic}

{Full, Automatic}

{ymin, All}

{{xmin, xmax}, All}

Full

{All, ymax}

{Full, {ymin, Automatic}}

5

{ymin, ymax}

{{xmin, xmax}, {ymin, ymax}}

All

g

When showing a plot, Mathematica normally displays all values of the function in the given interval. However, if the function takes on very small or very large values on a small interval, Mathematica may decide to cut such values away from the plot so that the remaining parts of the function can be seen more clearly; this may happen if the value Automatic is used for PlotRange. To see the whole function, use the value All. The value Full also causes the whole function to be plotted but, in addition, the whole plotting range on x axis is included in the plot. A constant value such as 5 means, for Plot, the plot range {Full, {-5, 5}} and, for Graphics and ParametricPlot, the plot range {{-5, 5}, {-5, 5}}. [email protected]@[email protected], 8x, -1, 10
1.0 0.8 0.6 0.4 0.2

20 000

6000

15 000

4000

10 000

2000

5000 0

2

4

6

8

10

2

4

6

8

10

-1.0 -0.5

0.0

1.0 0.8 0.6 0.4 0.2 0.5

1.0

0.2 0.4 0.6 0.8 1.0

In the first plot, we use the default value {Full, Automatic} of PlotRange for Plot. The y range definition Automatic has, in this example, caused the function to be shown only up to approximately x = 9. The x range definition Full means that the whole x range H0, 10L is shown. In the second example, the value All is used to show the whole function up to x = 10. In the third plot, we again use the default value {Full, Automatic}. Thus, the whole x plotting range is included, although the function is not defined on @-1, 0L. In the fourth plot, we use the value All, and then all the points where the function is defined (and only these points) are shown. The ClippingStyle option can be used to define the style for how the clipped parts are displayed; see Section 7.4.1, p. 203. (PlotRangeClipping (Ÿ6) Whether graphics objects should be clipped at the edge of the region defined by PlotRange or should be allowed to extend to the selection rectangle; possible values: True c p , False g )

Chapter 7 • Graphics Options

191

7.2.3 Margins and Background PlotRegion Specifies margins around the plot inside the selection rectangle; examples of values: Automatic (means {{0, 1}, {0, 1}}), {{xmin, xmax}, {ymin, ymax}} (ImageMargins Specifies margins (in printer’s points) outside the selection rectangle; examples of values: 0, Automatic, 15, {{left, right}, {bottom, top}}) Background Color of the background; examples of values: None, LightGray

Each plot has a display area that can be seen by clicking the plot: A rectangle around the plot appears. The curve normally fills this area, but with PlotRegion we can define other ways for the curve to be placed in the display area. The plot region is given in scaled coordinates ranging from 0 to 1 in each direction. The default setting Automatic is the same as {{0, 1}, {0, 1}}, which is the whole display area. By specifying other values (values less than 0 and greater than 1 are allowed), we can adjust the margins around the curve in the display area. For example, plots with gray or colored backgrounds often look better with a somewhat reduced plot region (i.e., with larger margins). The second plot shown here has a wider margin around the plot than the first plot. In the third plot, the margin is outside the selection rectangle. [email protected] [email protected]@xD, 8x, 0, 2 p<, Background Ø LightGray, PlotRegion Ø AutomaticD, [email protected]@xD, 8x, 0, 2 p<, Background Ø LightGray, PlotRegion Ø 880.1, 0.9<, 80.1, 0.9<
1.0 1.0 0.5

0.5

-0.5

1

2

3

4

5

6

0.5 1 2 3 4 5 6

-0.5 -1.0

-1.0

-0.5

1

2

3

4

5

6

-1.0

(ImagePadding (Ÿ6) Extra space (in printer’s points) for objects such as thick lines and tick and axes labels; examples of values: All, None, 15, {{left, right}, {bottom, top}}) (PlotRangePadding (Ÿ6) How much further axes etc. should extend beyond the range of coordinates specified by PlotRange; examples of values: Automatic, None, {0.2, 0.5}) The first plot below shows that usually the axes are a little extended (2% in each direction) from the given x range and the range of y values. In the second plot, we use no padding, and in the third plot we use unusually wide padding. No padding is used if an explicit plot range is used.

[email protected]@xD, 8x, 0, 2 p<, PlotRangePadding Ø ÒD & êü 8Automatic, None, 80.5, 0.2<<

:

1.0

1.0

0.5

0.5 1

2

3

4

5

6

,

0.0

1.0 0.5

, 1

2

3

4

5

6

1

-0.5

-0.5

-0.5

-1.0

-1.0

-1.0

2

3

4

5

6

>

192

Mathematica Navigator

7.2.4 Fonts All text in a plot is, by default, written with the Times font of size 10. We can change the font properties at various levels: for all plots during a session, for all texts in a single plot, for all labels in a single plot, and for a text item inside a plot. Here is a summary: Setting font properties at various levels: SetOptions[Plot, BaseStyle Ø {font directives and options}]

For all plots in a session: For all texts in a plot: For all labels in a plot: For a text item: Note

that

the

BaseStyle Ø {font directives and options} LabelStyle Ø {font directives and options} Style[expr, {font directives and options}]

more

specific

style

options

AxesStyle,

TicksStyle,

FrameStyle,

and

FrameTicksStyle can be used to adjust fonts in axes labels, tick labels, frame labels, and frame tick

labels. See Section 7.3.5, p. 200, for a discussion of the hierarchy of styles on plots. Next, we consider BaseStyle, LabelStyle, SetOptions, and Style in detail. ‡ Setting Font Properties for All Texts or Labels in a Plot * BaseStyle Ø {font directives and options} (Ÿ6)

The font styles given in BaseStyle apply for all texts in a plot: for plot label, axes labels, tick labels, frame labels, frame tick labels, and Text primitives. In defining the style of font, we can use font directives such as 7 (font size), Bold, and Italic and font options such as FontFamily and FontColor. Examples: BaseStyle Ø 7 BaseStyle Ø 87, Bold, Italic< BaseStyle Ø 87, Bold, FontFamily Ø "Helvetica"<

In the next example, we use bold Helvetica in size 7:

[email protected]@xD, 8x, 0, 2 p<, AxesLabel Ø 8x, [email protected]<, BaseStyle Ø 87, Bold, FontFamily Ø "Helvetica"
2

3

4

5

6

x

-0.5 -1.0

The next boxes give font directives and font options. Font directives: n, Tiny, Small, Medium, Large, Smaller, Larger Bold, Italic, Underlined, Plain Red, LightBlue, GrayLevel[0.3], etc.

Chapter 7 • Graphics Options

193

Font options: FontFamily; examples of values: "Times", "Helvetica", "Courier" FontColor; examples of values: Red, Gray FontTracking; examples of values: "Narrow", "Condensed", "SemiCondensed", "Extended", "Wide" Background; examples of values: LightGray, LightBlue

Instead of the directives, we can use the options FontSize, FontWeight, FontSlant, and FontColor. If we want to define a color for all text with BaseStyle, a definition such as BaseStyle Ø Red causes the axes and labels to also be colored. Thus, font color should be defined by using FontColor, as in BaseStyle Ø {FontColor Ø Red}. If you export Mathematica figures in, for example, EPS form into another application such as TEX and encounter problems with special characters appearing in the plots, one solution may be to render the document in the front end (and not in the printer). To do this, choose Format @ Option Inspector…, set Show option values for to be notebook, then go to Notebook Options @ Printing Options @ PrintingOptions and change the value of GraphicsPrintingFormat from Automatic to RenderInFrontEnd. Now when you print a document, it is rendered in the front end. LabelStyle Ø {font directives and options} (Ÿ6) LabelStyle applies for all labels in a plot (i.e., for plot labels, axes labels, tick labels, frame labels, and frame tick labels) but not for Text primitives. ‡ Setting Font Properties for a Session

Usually, the same style of text is used for all plots in a document or in a session. The style definitions need not be done for each plot separately because we can set, with SetOptions, the value of BaseStyle so that the given value is used during the rest of the current session. SetOptions[Plot, BaseStyle Ø {font directives and options}]

For example, to use the Helvetica font of size 8 during a session, simply execute, at the beginning of the session, the following command: [email protected], BaseStyle Ø 88, FontFamily Ø "Helvetica"
If you want to use the same text style for several plotting commands, write, for example, [email protected], ListPlot, ListLinePlot<, BaseStyle Ø 88, FontFamily Ø "Helvetica"
The font properties can also be defined in the init.m file; the definitions then hold automatically for all sessions, unless you change the definitions (see Section 4.1.1, p. 96). ‡ Setting Font Properties for a Text Item

Sometimes we want to use varying font properties for several text items in a plot. We can then define the font used most often with the BaseStyle and use Style in places where we want to use special font properties. Style[expr, {font directives and options}] (Ÿ6)

194

Mathematica Navigator

The font directives and options need not even be given as a list; they can simply be written separated by commas. For colors, we need not use the FontColor option; just write the color specification. Here are some examples: f = [email protected] [email protected] ê [email protected];

[email protected], 8x, 0, 5<, PlotLabel Ø [email protected]@f, 8, BlueDD, ImageSize Ø 110D, [email protected], 8x, 0, 5<, AxesLabel Ø [email protected]Ò, 8, RedD & êü 8x, f
‰x tan-1 Hx L

x

x

: 80

,

80

,

60

60

‰x tan-1 Hx L

60

x

>

40 20

40

40

80

20

20 0

1

2

3

4

0

5

1

2

3

4

5

x

1

2

3

4

5

‡ Setting Font Properties in a Style Sheet

The font style in graphics can also be defined in a style sheet. In Section 3.2.2, p. 63, we showed how to change styles. Using this technique, we can change the style of Graphics cells. • Choose Edit Stylesheet… from the Format menu. A notebook appears with the title Private Style Definitions for …. • In the Enter a style name input field, write Graphics; the corresponding style definition cell appears in the document. Edit this cell with the Format menu by defining, for example, a font. • Thus far, the new Graphics style holds for the current notebook. You can also save the style sheet so that you can use it for any notebook (see Section 3.2.2). ‡ Formatting

(FormatType Format type of text used in a plot; examples of values: TraditionalForm, StandardForm, InputForm, OutputForm) These types of formatting are considered in Section 3.3.1, p. 70. The default is to use traditional formatting~that is, the type of formatting used in traditional mathematical typesetting: The font is Times, all variables are in italic, and all formulas are typeset according to traditional mathematical notation. These properties can be seen in the first plot: [email protected], 8x, 0, 5<, AxesLabel Ø 8x, y<, PlotLabel Ø f, FormatType Ø Ò, ImageSize Ø 110D & êü 8TraditionalForm, StandardForm<

‰x tan-1 HxL

‰x [email protected]

x :80 60 40 20

x

y

>

y

1

2

3

4

5

, 80 60 40 20 x

x 1

2

3

4

5

Chapter 7 • Graphics Options

195

7.2.5 Miscellaneous Options (BaselinePosition (Ÿ6) Where the baseline of a plot should be if the plot is combined with other plots or text; examples of values: Automatic, Axis, Bottom, Top, Center, Baseline) (AlignmentPoint (Ÿ6) How objects should by default be aligned when they appear in Inset; default value: Center) (ContentSelectable (Ÿ6) Whether and how content of a plot should be selectable; possible values: Automatic (double-click allows content selection), True (single clicks immediately select content objects), False (content objects cannot be selected)) (PreserveImageOptions (Ÿ6) Whether the size and margins of a plot should remain the same if the plotting command is executed anew; examples of values: Automatic (the properties should remain the same if not explicitly otherwise stated), True (the properties should remain the same), False (the previous properties are ignored)) (DisplayFunction Function to apply to a graphic; default value: $DisplayFunction With BaselinePosition we can ask to align several plots according to the x axis:

[email protected]@[email protected], 8x, 0, 2 p<, BaselinePosition Ø Axis, ImageSize Ø 120D, [email protected]@xD, 8x, 0, 3<, BaselinePosition Ø Axis, ImageSize Ø 120D, [email protected]@xD, 8x, 0, 3<, BaselinePosition Ø Axis, ImageSize Ø 120D<, " "D 20 15 1.0

10

0.5

5 1

2

3

4

5

1 0.5

6

1.0

1.5

2.0

2.5

3.0

0.5

-0.5

-1

-1.0

-2

1.0

1.5

2.0

2.5

3.0

7.3 Options for Axes, Frames, and Primitives 7.3.1 Plot Label PlotLabel Label of the plot; examples of values: None, Sin[x/2], "Function g(x)"

With Style we can modify the style of the plot label:

[email protected]@x ê 2D, 8x, 0, 4 p<, PlotLabel Ø [email protected] ê 2DD, [email protected]@x ê 2D, 8x, 0, 4 p<, PlotLabel Ø [email protected]@x ê 2D, 9, Red, FontFamily Ø "Helvetica"DD< x

x

sin

sin

2

:

2

1.0

1.0

0.5

, 2

4

6

8

10

>

0.5

12

2

-0.5

-0.5

-1.0

-1.0

4

6

8

10

12

196

Mathematica Navigator

Sometimes we want to vary a parameter in the label:

[email protected]@[email protected] xD, 8x, 0, 2 p<, PlotLabel Ø [email protected]"The graph of ", [email protected] xD
The graph of sinH2 x L

1.0

:

1.0

0.5

0.5 2

3

4

5

>

0.5

, 1

The graph of sinH3 x L 1.0

,

6

1

2

3

4

5

6

1

-0.5

-0.5

-0.5

-1.0

-1.0

-1.0

2

3

4

5

6

Next, we give a plot a more complete caption:

[email protected]@x ê 2D, 8x, 0, 4 p<, ImageSize Ø 160, PlotLabel Ø [email protected]@[email protected]"Figure 1.1 ", BoldD, "The graph of ", [email protected] ê 2D
x Figure 1.1 The graph of sin

1.0

2 1.0

:

0.5 0.5

, 2 2

4

6

-0.5 -1.0

8

10

12

4

6

8

10

12

>

-0.5 -1.0

Figure 1.1 The graph of sinI 2 M x

The PlotLabel option puts the caption on top of the plot. However, the traditional position of a figure caption is on the bottom of the plot; this can be done with the Labeled command, as can be seen from the second plot. For more about Labeled, see Section 3.3.1, p. 72.

7.3.2 Axes and Ticks ‡ Axes

, False g , {True, False} * AxesOrigin Point where the axes cross; examples of values: Automatic, {0, 0} AxesLabel Labels for the axes; examples of values: None, y, {x, None}, {x, y} (AxesStyle Style of the axes, axes labels, tick marks, and tick labels; examples of values: {}, Thick, Blue, Arrowheads[0.07], Directive[Thick, Blue, 12, Italic]

* Axes Whether to draw the axes; examples of values: True

cp

The point where the axes cross is AxesOrigin. Its default value is determined by an algorithm; this method usually chooses the point {0, 0} if it is within or close to the region defined by PlotRange. Axes labels are placed at the ends of the axes (frame labels, instead, are in the middle of the frame edges). If the axes labels are long, consider using a frame instead of axes (see Section 7.3.3, p. 198). The default thickness of axes and the major tick marks is AbsoluteThickness[0.25], and that for the minor tick marks is AbsoluteThickness[0.125]. With Arrowheads, we can draw arrows at the ends of the axes.

Chapter 7 • Graphics Options

197

[email protected] + [email protected], 8x, 1, 6<, AxesLabel Ø 8x, y
3.0

3.0

2.5

: 2.0

2.0

2.5

,

2.5

1.5

,

1.0

1.5

1.5

0.5 2

3

4

5

x

6

>

2.0

1

2

3

4

5

6

2

3

4

5

‡ Defining Positions of Ticks ** Ticks Tick on the axes; simple examples of values: Automatic, None, {{p, 2p}, Automatic}, {Automatic, {-1, 0, 1}}, {{p, 2p}, {-1, 0, 1}} TicksStyle (Ÿ6) Style of tick marks and tick labels; examples of values: {}, Blue, Directive[Thick, Blue, 12]

The general form of the value of Ticks is {xticks, yticks}. We can define ticks on both axes or let Mathematica choose the ticks on one of the axes. The automatic algorithm often uses appropriate ticks but frequently also too many ticks, especially if the plots are scaled to be small (as in this book). In particular, the minor tick marks (without labels) between the major tick marks (with labels) are often unnecessary. A few carefully selected tick marks often suffice. Indeed, Ticks is perhaps the option I use most often. For example, [email protected]@xD, 8x, 0, 2 p
1.0

:

0.5 1

2

3

4

5

6

,

p

2p

>

-0.5 -1.0

-1

In the second plot, we asked for only six ticks. Note, however, that we got only four tick labels: The labels on the x and y axis at 0 were not drawn. Indeed, tick labels on the axes origin are not displayed. ‡ Defining Labels, Lengths, and Styles of Ticks Ticks has more advanced forms, where we can define~in addition to the positions of the tick marks~

the tick labels and the length and style of the tick marks. In the next box, we give forms of a single tick and examples in which each form is used to define two ticks on the x axis (on the y axis, the default ticks are used). position

Example: {{p, 2p}, Automatic} {position, label}

Example: {{{p, a}, {2p, b}}, Automatic} {position, label, {poslength, neglength}}

Example: {{{p, a, {0.05, 0}}, {2p, b, {0.05, 0}}}, Automatic}

198

Mathematica Navigator

{position, label, {poslength, neglength}, style}

Example: {{{p , a, {0.05, 0}, Red}, {2p, b, {0.05, 0}, Red}}, Automatic} Often, when plotting mathematical figures, we do not want numerical tick labels but, rather, a few symbolic labels. Then we can define, with Ticks, the positions of the labels and the labels. The next figure is an example: aa = 80.2, 0<; bb = 80.8, 0<; cc = 80, [email protected]<; dd = 80, [email protected]<; ee = 80.2, [email protected]<; ff = 80.8, [email protected]<;

[email protected]@xD, 8x, 0, 1<, AxesOrigin Ø 80, 0<, Ticks Ø 8880.2 , a<, 80.8, b<<, [email protected], c<, [email protected], d<<<, Epilog Ø [email protected], ee, aa
c

a

b

Tick labels are, by default, written in traditional format. This may sometimes make the labels somewhat large relative to the figure. Defining the labels as strings may be a solution: [email protected]@xD, 8x, 0, 2 p<, Ticks Ø 88p ê 2, p, 3 p ê 2, 2 p<, 8-1, 1<
:

1

, p 2

p

3p

pê2

2p

p

3pê2

2p

>

2

-1

-1

7.3.3 Frame and Frame Ticks * Frame Whether to draw a frame; examples of values: False, True, {True, True, False, False} * FrameLabel Labels for the frame; examples of values: None, {x, y}, {"bottom", "left", "top", "right"} * RotateLabel Whether to rotate the labels for the vertical edges; possible values: True, False FrameStyle Style of the frame, frame labels, frame tick marks, and frame tick labels; examples of

values: Automatic, Blue, Directive[Thick, Red, 12, Italic] * FrameTicks Frame tick marks on the frame; simple examples of values: Automatic, None, All (on

all edges), {{0, p, 2p}, {-1, 1}, None, None} FrameTicksStyle (Ÿ6) Style of frame tick marks and frame tick labels; examples of values: {}, Red, Directive[Thick, Red, 12, Bold]

For most frame options (not for RotateLabel), we can define the properties separately on each of the four edges of the frame. In the previous box, the properties were given in the form {bottom, left, top, right}. The properties can also be given in the form {{left, right}, {bottom, top}}. Here are some examples:

Chapter 7 • Graphics Options

199

[email protected]@xD, 8x, -p ê 2, 5 p ê 2<, PlotRange Ø 8-1.3, 1.3<, Frame Ø True, FrameLabel Ø 8x, y<, RotateLabel Ø FalseD, [email protected]@xD, 8x, -p ê 2, 5 p ê 2<, AxesLabel Ø 8x, y<, PlotRange Ø 8-1.3, 1.3<, Frame Ø True, FrameTicks Ø 880, p, 2 p<, 8-1, 0, 1<, None, None
y

1.0

:

1

0.5

y

1

>

0.0

,

-0.5

x

0

, p

-1.0 0

2

4

6

-1

8

x

0

p

2p

x

-1

2p

As the first plot shows, frame labels are placed midway on the edges (axes labels are placed at the ends of the axes). The default value of RotateLabel is True, which means that the frame labels on the vertical parts of the frame are rotated so that they read from bottom to top. A short label such as y looks better and is easier to read when not rotated. If we want a frame, then the figure often looks better if there is somewhat more space around the curve. This can be done with PlotRange. In the second plot, we have defined our own ticks. The default is that there are tick marks on all edges but tick labels only on the bottom and left edges. If we define our own x and y ticks, they are used on all four edges, but with None we can remove the ticks from the edges on which we do not want them. Frame ticks are defined in the same way as axes ticks (see Section 7.3.2, p. 196). In the third plot, we used the Framed command instead of the Frame option; for Framed, see Section 3.3.1, p. 72.

7.3.4 Grid Lines GridLines How the grid lines are drawn; simple examples of values: None, Automatic, {None, Automatic}, {None, {-1,0,1}}, {{0,1,2}, {-1,0,1}} (GridLinesStyle (Ÿ6) Style of the grid lines; examples of values: {}, Dashed, Directive[LightGray, Dashed])

Ticks often suffice to give information about the values of the coordinates. However, if we want to read approximate coordinates from a figure, then grid lines may help us. The value Automatic of GridLines draws lines on the major ticks and colors them gray. For example, [email protected]@xD, 8x, 0, 2 p<, Ticks Ø 88p, 2 p<, 8-1, 1<<, GridLines Ø ÒD & êü 8 Automatic, 8None, Automatic<, 88p ê 2, p, 3 p ê 2, 2 p<, 8-1, -0.5, 0.5, 1<<< 1

:

1

p

-1

2p

,

1

p

-1

2p

,

p

-1

2p

>

200

Mathematica Navigator

7.3.5 Hierarchy of Styles For all of the components of a plot, we have options to give the components the styles we like most. We have very general options such as BaseStyle that affect most components of a plot. We have options such as AxesStyle that affect many components. We have special options such as FrameTicksStyle that affect only a few components. Finally, with either the Style command or special inputs we can control the style of single components. Let us look at the various components of a plot and how they can be styled with options. First, the curve in a plot can be styled with PlotStyle (ColorFunction can also be used); the BaseStyle option has no effect on the curve. ‡ Plot Label BaseStyle affects the style of a plot label. However, if LabelStyle is used, it overrides possible BaseStyle and so has a higher priority. Finally, if we use the Style command, it overrides possible

other options. The following examples illustrate this hierarchy of the options:

[email protected]@xD, 8x, 0, 2 p<, PlotLabel Ø [email protected], BaseStyle Ø BlueD, [email protected]@xD, 8x, 0, 2 p<, PlotLabel Ø [email protected], BaseStyle Ø Blue, LabelStyle Ø GreenD, [email protected]@xD, 8x, 0, 2 p<, BaseStyle Ø Blue, LabelStyle Ø Green, PlotLabel Ø [email protected]@xD, RedDD<

sinHxL

sinHxL

1.0 :

0.5

-0.5

sinHxL

1.0

1.0

0.5 1

2

3

4

5

-1.0

6

>

0.5

,

, -0.5

1

2

3

4

-1.0

5

6

-0.5

1

2

3

4

5

6

-1.0

‡ Axes

Next, we consider options and commands that can be used to adjust the styles of components related to axes. We prepare a table: [email protected]@[email protected]"Component", BoldD<, [email protected]Ò, "Input", FontFamily Ø "Courier"D & êü 8BaseStyle, LabelStyle, AxesStyle, TicksStyle, Style
Component

BaseStyle

Axes

μ

Axes labels

μ

Axes tick marks

μ

Axes tick labels

μ

LabelStyle

AxesStyle

TicksStyle

Style

μ μ μ

μ

μ

μ

μ

μ

μ

μ

With  we have denoted the components that each option or command can control. BaseStyle, LabelStyle, AxesStyle, and TicksStyle are options, and Style is a command.

Chapter 7 • Graphics Options

201

The options and commands are mentioned in the table in the order of increasing priority. BaseStyle affects all the components mentioned in the table. However, if LabelStyle is used, it has higher priority for the labels. If AxesStyle is used, it has still higher priority over BaseStyle and LabelStyle. TicksStyle has the highest priority for axes tick marks and tick labels. However, if we use the Style command for axes or tick labels, it overrides possible options.

7.3.6 Primitives ‡ Adding Primitives with Prolog and Epilog

Occasionally, we may want to add some components to a plot. We may want to have clarifying text, an important point, an arrow, or a line. Such small additions may considerably improve the quality of a plot: They guide the eyes of the reader to important aspects of the plot. The options Prolog and Epilog are the tools for making such additions. (Prolog Graphics primitives to be plotted before the main plot; examples of values: {}, {Red, PointSize[Medium], Point[{3, 2}]}) ** Epilog Graphics primitives to be plotted after the main plot; examples of values: {}, {Red, PointSize[Medium], Point[{3, 2}]}

The values of Prolog and Epilog are lists of graphics directives and primitives. Directives and primitives were explained in Chapter 6. For easy reference, we list here the four primitives that are most useful when using Prolog and Epilog. Point[p] Point at p Line[{p1, …, pn}] Line through points p1, ..., pn Text[expr, p, q] The point q, expressed in text coordinates, of expr is at the point p Arrow[{p1, p2}] Arrow from p1 to p2 ‡ Example

We have already used some primitives with the Epilog option in a few examples; see Sections 6.2.6, p. 163 (Point, Text), 6.2.10, p. 175 (Inset), and 7.1.1, p. 183 (Point, Text, Arrow). Many more examples are in the forthcoming chapters. In the next example, we use the primitives Point, Line, Text, and Arrow: [email protected]@xD + 1, [email protected]<, 8x, 0, 1.5<, PlotRange Ø 880, 1.9<, 80, 1.55<<, ImageSize Ø 220, Ticks Ø 880.5, 1, 1.5<, 80.5, 1, 1.5<<, Epilog Ø [email protected]@xD + 1, 81.55, 1.42<, 8-1, 0
1.5

x 1 logHx L + 1  0.5

0.5

1

1.5

x

202

Mathematica Navigator

Here, we defined a large enough PlotRange to include all the primitives in the plot. Indeed, the default value of PlotRange does not take into account possible added primitives. ‡ Disappearing Primitives

We may also have the problem of disappearing primitives. Remember what we said in Section 5.1.2, p. 125, about options with Show: If plots to be combined with Show have different values for some options, the values of the first plot are applied. Thus, if we combine two or more plots with Show~each having an Epilog option~then Show takes on the value of Epilog given in the first figure. This means that all of the graphics primitives in the other figures are left out. You may think the problem is solved by writing an Epilog in Show to add the lacking primitives. In reality, the primitives of the first figure are now lacking. Thus, if you intend to combine several figures with Show, prepare to use Epilog also in Show: Write in the Epilog option all the primitives of the component figures. If you do not need the intermediate figures as such, do not add primitives into them but only into the final combined figure. However, if you plot the primitives with Graphics, then the problem does not occur; this method is considered next. ‡ Adding Primitives with Graphics Prolog and Epilog are not the only ways to add graphics primitives; we can also use Graphics (see

Section 6.1.1, p. 152). In fact, we can separately plot the main figure with Plot (or with another command) and the primitives with Graphics and combine the two plots with Show. For example,

8p1 = [email protected]@xD + 1, [email protected]<, 8x, 0, 1.5<, PlotRange Ø 880, 1.9<, 80, 1.55<<, Ticks Ø 880.5, 1, 1.5<, 80.5, 1, 1.5<
1.5

x

:

1

logHx L + 1 

, 0.5

0.5

1

1.5

[email protected], p2, ImageSize Ø 220D logHx L + 1

1.5

x 1 logHx L + 1  0.5

0.5

1

1.5

x

x

>

Chapter 7 • Graphics Options

203

7.4 Options for the Curve 7.4.1 Plot Style * PlotStyle

cp

Style(s) of the curve(s); examples of values: Automatic, Thickness[Medium],

Directive[Thick, Red, Dashed]

When plotting 2D curves, PlotStyle defines the thickness, dashing, and color of the curves. The default value Automatic means a thin, nondashed curve whose color is Hue[0.67, 0.6, 0.6]. The style can be defined with graphics directives. Thickness can be defined, among others, with Thickness and AbsoluteThickness, dashing with Dashing and AbsoluteDashing, and color with, for example, Red. For thickness and dashing, see Section 6.2.2, p. 156, and for colors, see Section 6.2.8, p. 168. PlotStyle is handy for distinguishing different curves in the same plot. Note that a good way to

identify the curves is with the use of Tooltip (see Section 5.1.2, p. 122). We can also add a legend telling which style belongs to which curve (see Section 7.4.7, p. 208). With Directive (see Section 6.1.2, p. 155), the PlotStyle option can be written in the following forms: Style definitions for one curve: PlotStyle Ø Directive[s1, s2, … ]

Style definitions for several curves: PlotStyle Ø Directive[s1, s2, … ] Same style for each curve PlotStyle Ø {Directive[s11, s12, … ], Directive[s21, s22, … ], … } Different styles for the

curves Here, each si or sij is a graphics directive such as Red, Thick, or Dashed. The default style is denoted by the empty list {}. If a style is defined only with a single directive, then Directive is not needed. Some examples: [email protected]@[email protected], 8x, 0, 2 p<, PlotStyle Ø RedD, [email protected]@xD, 8x, 0, 2 p<, PlotStyle Ø [email protected], ThickDD, [email protected]@xD, [email protected]<, 8x, 0, 2 p<, PlotStyle Ø [email protected], ThickDD, [email protected]@xD, [email protected]<, 8x, 0, 2 p<, PlotStyle Ø [email protected], ThickD, [email protected], ThickD
1.0

1.0

1.0

0.5

0.5

0.5

0.5

-0.5 -1.0

1

2

3

4

5

6

-0.5 -1.0

1

2

3

4

5

6

-0.5 -1.0

1

2

3

4

5

6

-0.5

1

2

3

4

5

6

-1.0

(ClippingStyle c (Ÿ6) How to indicate clipped parts that fall outside of the plot range; examples of values: None, Automatic, Red, {Blue, Red}) Parts of a plot may be clipped as discussed previously. The ClippingStyle option can be used to define the way that clipped parts of the plot are shown:

204

Mathematica Navigator

[email protected]@[email protected], 8x, 0, 2 p<, PlotRange Ø 0.5, ClippingStyle Ø ÒD & êü 8None, Automatic, Red, 8Blue, Red<<, ImageSize Ø 420D 0.4 0.2 -0.2 -0.4

0.4 0.2 1

2

3

4

5

6

-0.2 -0.4

0.4 0.2 1

2

3

4

5

6

-0.2 -0.4

0.4 0.2 1

2

3

4

5

6

-0.2 -0.4

1

2

3

4

5

6

The first plot shows the default way that clipped parts are indicated: Nothing is plotted. With the value Automatic, we get a dashed line. We can give the line some directives such as a color or two colors: The first color is used at the bottom and the second at the top.

7.4.2 Color Function (ColorFunction c p (Ÿ6) Function that determines the color of the curve; examples of values: Automatic, (Hue[#2] &), (RGBColor[#2, 0, 1 - #2] &), "Rainbow") (ColorFunctionScaling c p (Ÿ6) Whether arguments to a color function should be scaled to lie between 0 and 1; examples of values: True, False) With ColorFunction, we can get colors that vary according to the values of x and y. The color function is a pure function whose arguments are #1 (corresponds to x) and #2 (y); in ParametricPlot, an argument can also be #3 (the parameter). Many gradients (e.g., "Rainbow") useful as a color function can be found from the ColorSchemes palette. Usually, it is useful for the arguments of a color function to be scaled to H0, 1L because the arguments of all color schemes can be in this interval. [email protected]@xD, 8x, 0, 2 p<, PlotStyle Ø Thick, ColorFunction Ø ÒD & êü [email protected]Ò2D &L, [email protected]Ò2, 0, 1 - Ò2D &L, "Rainbow"<

:

,

,

>

7.4.3 Filling c (Ÿ6) Type of filling to use; examples of values: None, Axis, Bottom, Top, 0.3, True (FillingStyle c (Ÿ6) Style of filling; examples of values: Automatic, Red, {Blue, Red} (different style for negative and positive values), Directive[Opacity[0.3], Blue])

Filling

Filling was considered in Section 5.2.4, p. 135.

Chapter 7 • Graphics Options

205

[email protected]@1, xD, 8x, 0, 20<, Filling Ø AxisD, [email protected]@xD, [email protected] + 1D<, 8x, 0, 100<, Filling Ø TrueD<

:

>

,

7.4.4 Mesh Points Mesh

cp

How many mesh points should be drawn; examples of values: None c , Automatic p , 10,

Full, All, {{0}} cp

(Ÿ6) How to determine the placement of the mesh points; examples of values: p , {#2 &}, The style of mesh points; examples of values: Automatic, PointSize[Small],

MeshFunctions c

{#1 &} , Automatic cp

MeshStyle

Directive[Red, PointSize[Medium]]

(MeshShading Blue})

cp

(Ÿ6) How to shade regions between mesh points; examples of values: None, {Red,

By a mesh for a curve, we mean points on the curve. With Mesh, we can ask a given number of points that correspond to equally spaced x points. The value Full means that the initial sample points are drawn. With the value All, we get the final sample points (for sampling, see Section 7.4.6, p. 207): [email protected]@xD, 8x, 0, 2 p<, Mesh Ø Ò, MeshStyle Ø [email protected], [email protected] & êü 815, Full, All< 1.0

:

1.0

0.5

1.0

0.5 1

2

3

4

5

6

,

0.5 1

2

3

4

5

6

,

1

-0.5

-0.5

-0.5

-1.0

-1.0

-1.0

2

3

4

5

6

>

With Mesh, we can show points at which a function or a difference of two functions has a given value, for example, 0. Another way is to use Epilog: f = x ^ 5 - 7 x ^ 3 + 9 x; g = 2 x; [email protected], 8x, -2.5, 2.5<, Mesh Ø 880<<, MeshFunctions Ø 8Ò2 &<, MeshStyle Ø [email protected], [email protected], g<, 8x, -2.5, 2.5<, Mesh Ø 880<<, MeshFunctions Ø 8Hf - gL ê. x Ø Ò1 &
:

10

5 -2

5

,

-1

10

1

2

-2

5

,

-1

1

2

-2

-1

1

-5

-5

-5

-10

-10

-10

2

>

206

Mathematica Navigator

7.4.5 Exclusions and Region Function Exclusions

cp

(Ÿ6) The x points that are excluded in plotting; examples of values: Automatic,

None, {p/2, 3 p/2}, {Cos[x] ã 0} ExclusionsStyle

cp

(Ÿ6) What to draw at excluded points; examples of values: None, Directive[

Blue, Dashed], {None, Directive[Red, PointSize[Medium]]}

Possible steps in functions are automatically plotted discontinuously, but by giving the Exclusions style the value None, we can also get a vertical line: [email protected]@88-1, x < 1<, 81, x ¥ 1<
:

1.0

0.5

0.5

, 0.5

1.0

1.5

2.0

0.5

-0.5

-0.5

-1.0

-1.0

1.0

1.5

2.0

>

We can give the vertical line a suitable style and we can also get points at the ends of the step: [email protected]@88-1, x < 1<, 81, x ¥ 1<
1.0

1.0

0.5

0.5 0.5

1.0

1.5

2.0

,

1.0 0.5 0.5

1.0

1.5

2.0

,

0.5

-0.5

-0.5

-0.5

-1.0

-1.0

-1.0

1.0

1.5

2.0

>

Sometimes we want to indicate the value of the function at a point of discontinuity. One way to do this is to use disks and circles: [email protected]@88-1, x < 1<, 81, x ¥ 1<
1.0

1.5

2.0

-0.5 -1.0

For infinite jumps, a vertical line is automatically drawn. To get rid of the line, define, with Exclusions, points to avoid either explicitly as a list or implicitly by an equation:

Chapter 7 • Graphics Options

207

[email protected]@xD, 8x, 0, 2 p
:

6

6

6

4

4

4

2

2

-2

1

2

3

4

5

6

, -2

2 1

2

3

4

5

6

, -2

-4

-4

-4

-6

-6

-6

1

2

3

4

5

6

>

(RegionFunction c p (Ÿ6) Specifies the region to include in the plot drawn; examples of values: (True &), (Abs[#2] > 0.7&)) The basic way to control the x values is to give a suitable interval in the plotting command. The basic way to control the y values is to use PlotRange. More complex rules that determine the values of x and y for which the curve is plotted can be given with RegionFunction. A point is included in the plot if the region function at that point gives True. The arguments of the pure function are #1 (corresponds to x) and #2 (y); in ParametricPlot, an argument can also be #3 (the parameter). [email protected]@xD, 8x, 0, 2 p<, RegionFunction Ø [email protected]Ò2D < 0.6 »» [email protected]Ò2D > 0.8 &LD 1.0 0.5 1

2

3

4

5

6

-0.5 -1.0

7.4.6 Plotting Algorithm Mostly, the default values of the following options give very good results. In special cases, the use of some of these options may improve the quality of the plot. cp

Number of initial sampling points; examples of values: Automatic, 100 (Ÿ6) The maximum number of recursive subdivisions allowed; examples of values: Automatic, 8 WorkingPrecision c p (Ÿ6) The precision used in computations; examples of values: MachinePrecision, 20 (Evaluated c p (Ÿ6) Whether the expression to be plotted is evaluated before the expression is sampled; possible values: Automatic, True, False) (PerformanceGoal c p (Ÿ6) What aspect of performance to try to optimize; examples of values: $PerformanceGoal, "Quality", "Speed") (EvaluationMonitor c p (Ÿ6) Expression to evaluate at every function evaluation; examples of values: None, Sow[{x, Sin[x]}]) PlotPoints

MaxRecursion

cp

Plot works by first sampling the function at some equally spaced points specified by PlotPoints. If the function changes rapidly between two points, the interval is divided into two smaller intervals. This subdivision is continued until the curve resulting by joining the sample points with lines is smooth enough. However, subdivisions are done at most MaxRecursion times. In this way, Plot is adaptive, and, accordingly, the resulting plot is usually sufficiently smooth and accurate.

208

Mathematica Navigator

As an example, we plot a function and collect all the points where the function is evaluated: a = [email protected]@[email protected], 8x, 0, 2 p<, EvaluationMonitor ß [email protected], [email protected]
(Note the delayed rule ß that is written as :>; for Sow and Reap, see Section 18.2.3, p. 564.) The next plot shows all the points (more than 400) where the function was evaluated to get the curve: [email protected], 1T, PlotStyle Ø [email protected], Filling Ø Axis, AspectRatio Ø 0.2, ImageSize Ø 420D

We see that where the function changes rapidly, more points are calculated than where the function behaves almost linearly. Next, we plot a function that behaves wildly near the origin:

[email protected]@1 ê xD, 8x, 0, 0.1<, PerformanceGoal Ø "Speed", AspectRatio Ø 0.4D, [email protected]@1 ê xD, 8x, 0, 0.1<, AspectRatio Ø 0.4D, [email protected]@1 ê xD, 8x, 0, 0.1<, MaxRecursion Ø 8, AspectRatio Ø 0.4D< :

1.0

1.0

0.5

0.5

1.0 0.5

, -0.5

0.02

0.04

0.06

0.08

-1.0

0.10

, -0.5

0.02

0.04

0.06

-1.0

0.08

0.10

-0.5

0.02

0.04

0.06

0.08

0.10

>

-1.0

The numbers of sampled points are as follows:

[email protected]%PÒTP1, 1, 3, 2, 1TD & êü 81, 2, 3<

8182, 1669, 4105<

In the first figure, we rejected the goal of quality and, instead, asked to get a plot rapidly; only 182 sample points were calculated. In the second plot, Plot gradually increased the number of sampled points up to 1669 (MaxRecursion was 6), but by comparing the two figures, we see that even this is not sufficient. In the third figure, we allowed 8 recursive subdivisions and ended with 4105 points, and now the result is good. The WorkingPrecision option can be useful if the computation of the values of the function involves round-off errors. See an example in Section 12.2.3, p. 407. When Plot samples the expression to be plotted, the expression is held in an unevaluated form. However, sometimes it is necessary for the expression to be evaluated before sampling. This can be achieved with the option Evaluated Ø True; this is equivalent to enclosing the expression with the Evaluate command.

7.4.7 Legends ‡ Legends with Primitives

If we have several curves in the same plot, it is useful to identify the curves in some way. On the screen, a good way is to use Tooltip; see Section 5.1.2, p. 122.

Chapter 7 • Graphics Options

209

Another good way is to place a suitable Text primitive near each curve; see an example in Section 7.3.6, p 201. This method has several advantages. It is simple to implement, we need not look at a separate legend, and we can use the same style for each curve (as was done in the example in Section 7.3.6). Still another way to identify the curves is the use of a legend. This can easily be done with graphics primitives in an Epilog option, but we also have a package for legends. Here is an example of the use of Epilog: [email protected]@xD, [email protected]<, 8x, 0, 2 p<, AspectRatio Ø 0.4, PlotRange Ø 88-0.1, 9.3<, All<, Ticks Ø 88p, 2 p<, 8-1, 1<<, PlotStyle Ø 8Black, 8Black, [email protected]
1

cosHx L p

2p

-1

If the legend is placed outside the x range of the curves as above, then PlotRange must be used to extend the x range so that the legend is within it. In the previous example, the extended x range causes the x axis to continue from 2p to 9.6. To stop the x axis at 2p, we have defined white as the style of the x axis and drawn the x axis ourselves with the Line primitive. ‡ Legends with a Package

The PlotLegends` package (see PlotLegendsêguideêPlotLegendsPackage`) adds some new options for Plot enabling the use of legends. Note that this holds only for Plot and not for any other plotting command. For other commands, the package defines the ShowLegend command. Before listing the legend options, we present two examples. In the first example, we have used the default style of the legend. << PlotLegends`

[email protected]@xD, [email protected]<, 8x, 0, 2 p<, PlotStyle Ø 88<, [email protected]
sinHx L

1.0

0.5

:

0.5 -0.5 sinHx L

-1.0 cosHx L

1

2

3

4

5

6

,

cosHx L 1

-0.5 -1.0

2

3

4

5

6

>

210

Mathematica Navigator

Options for the legend and its position, size, and orientation: ** PlotLegend The texts in a legend (mandatory legend option with Plot); an example of value: {Sin[x], Cos[x]} ** LegendPosition Position of the lower left corner of the legend box (in a coordinate system in

which the center of the figure is {0, 0} and the longest side of the plot runs from -1 to 1); default value: {-1.2, -0.82} ** LegendSize Size of the legend box (in the same units as LegendPosition); examples of values: Automatic, 0.6, {width, height} LegendOrientation Direction of the legend; possible values: Vertical, Horizontal Options for the style of the legend box and its shadow: LegendBorder Style of the border line; default value: Automatic LegendBorderSpace Space between the border and its content; default value: Automatic LegendBackground Color of the background; default value: Automatic ** LegendShadow Offset of the shadow from the legend box (in the same units as LegendPosition); examples of values: Automatic, None (no border and no shadow), {0, 0} (no shadow), {xoffset, yoffset} ShadowBackground Color of the shadow; default value: GrayLevel[0]

Options for the key boxes, texts, and legend label: LegendSpacing Space around each key box; default value: Automatic LegendTextSpace The width of the space of each text; default value: Automatic LegendTextOffset Offset of a text from a key box; default value: Automatic LegendTextDirection Direction of text; default value: Automatic LegendLabel Label of the legend box; default value: None LegendLabelSpace Space above and below the label; default value: Automatic ShowLegend[graphic, {{{key1, text1}, {key2, text2}, … }, opts}] Show graphic with a

legend containing the key graphics or key colors key1, key2, … and texts text1, text2, …; modify the legend with the legend options opts

7.5 Options for Surface Plots 7.5.1 Summary ‡ Introduction

In this section, we list all the options of Plot3D, ParametricPlot3D, and Graphics3D, with short descriptions and with some common values (Graphics3D was explained in Section 6.2.11, p. 176). The default value of an option is mentioned first, and then we mention either all other possible values or some examples of other values (the examples are simple; more advanced forms may exist). The options are divided into three groups: • Global options: These are options to modify global aspects of the plot~that is, to adjust how the plot looks in general. This means, for example, adjusting the form, size, plot range, various margins, fonts, or viewpoint.

Chapter 7 • Graphics Options

211

• Local options: These are options to modify local components of a plot such as plot label, axes, ticks, bounding box, face grids, or add-ons. • Options for the surface: These are options to modify the curve produced by Plot3D or ParametricPlot3D. This means, for example, adjusting the style, filling, mesh, or exclusions or controlling the plotting algorithm. All of the options in the first two groups are common to all three plotting commands mentioned. However, options in the third group are applicable only to Plot3D or ParametricPlot3D. Options and their default values applicable only to certain commands are expressed in the following lists by a superscript after the option name or value: s

: applicable to Plot3D (shorthand for surface) : applicable to ParametricPlot3D (shorthand for parametric) g : applicable to Graphics3D (shorthand for graphics)

p

For example, PlotStyle s p means that this option applies to Plot3D and ParametricPlot3D but not to Graphics3D, and False g means that the default value of the option in question (Axes) is False for Graphics3D. Ten options assumed to be somewhat important are marked with an asterisk ( *). A single parenthesis indicates several options that most of us will seldom need. The remaining options, without any special markings, may sometimes be useful. Of course, the given classification of the options according to importance reflects my personal impression. You may well have a different classification. ‡ Global Options

With Plot3D, ParametricPlot3D, and Graphics3D, the following options can be used to adjust some global aspects of a plot. Options for form and size: * BoxRatios Ratios of side lengths of the bounding box; default values: {1, 1, 0.4} s , Automatic

pg

(AspectRatio Ratio of height to width of the plotting rectangle; default value: Automatic) ImageSize The absolute size (in printer’s points) of the plot; examples of values: Automatic, Full, All, width, {width, height}, {maxsize}, {{maxwidth}, {maxheight}} An option for plot range: * PlotRange Ranges for x, y, and z in the plot; examples of values: Automatic g

,

{zmin,Automatic},

{Full, Full, Automatic} s ,

{zmin,All},

{Full, Full, All},

Full,

{All,zmax},

{{xmin, xmax}, {ymin, ymax}, All},

5,

{zmin,zmax},

{{xmin, xmax}, {ymin, ymax}, {zmin, zmax}}

All

,

p

Options for margins and background: PlotRegion Specifies margins around the plot inside the selection rectangle; examples of values: Automatic (means {{0, 1}, {0, 1}}), {{xmin, xmax}, {ymin, ymax}} SphericalRegion Whether to leave room in the plotting rectangle for a sphere enclosing the bounding box; possible values: False, True (ImageMargins Specifies margins (in printer’s points) outside the selection rectangle; examples of values: 0, Automatic, 15, {{left, right}, {bottom, top}}) (ImagePadding (Ÿ6) Extra space (in printer’s points) for objects such as thick lines and tick and axes labels; examples of values: All, None, 15, {{left, right}, {bottom, top}})

212

Mathematica Navigator p

(PlotRangePadding (Ÿ6) How much farther axes etc. should extend beyond the range of coordinates specified by PlotRange; examples of values: Automatic, None, {0.2, 0.5}) Background Color of the background; examples of values: None, LightGray Options for fonts and formatting: * BaseStyle (Ÿ6) Style of texts; examples of values: {}, {9, Bold, FontFamily Ø "Helvetica"} LabelStyle (Ÿ6) Style of all labels; examples of values: {}, {9, Bold, FontFamily Ø "Helvetica"} (FormatType Format type of text used in a plot; examples of values: TraditionalForm, StandardForm, InputForm, OutputForm) Options for viewpoint and lighting: * ViewPoint Point (in a scaled coordinate system) from which the surface is viewed; default value: {1.3, -2.4, 2} RotationAction (Ÿ6) How to render the plot if rotated with the mouse; examples of values: "Fit"

(after rotation, the plot is rescaled to fit into the image region), "Clip" (after rotation, the plot is not rescaled and so may be clipped) (ViewAngle (Ÿ6) Angle of the field of view; default value: Automatic) (ViewCenter Point (in scaled coordinates) to display at the center; default value: {1/2, 1/2, 1/2}) (ViewMatrix (Ÿ6) Explicit transformation matrix; default value: Automatic) (ViewRange (Ÿ6) Range of viewing distances to include; default value: All) (ViewVector (Ÿ6) Position and direction of a simulated camera; default value: Automatic) (ViewVertical Direction to make vertical; default value: {0, 0, 1}) Lighting What simulated lighting to use; simple examples of values: Automatic, "Neutral", None Miscellaneous options: (BaselinePosition (Ÿ6) Where the baseline of a plot should be if the plot is combined with other plots or text; examples of values: Automatic, Axis, Bottom, Top, Center, Baseline) (AlignmentPoint (Ÿ6) How objects should by default be aligned when they appear in Inset; default value: Center) (ContentSelectable (Ÿ6) Whether and how content of a plot should be selectable; possible values: Automatic (double-click allows content selection), True (single clicks immediately select content objects), False (content objects cannot be selected)) (PreserveImageOptions (Ÿ6) Whether the size and margins of a plot should remain the same if the plotting command is executed anew; examples of values: Automatic (the properties should remain the same if not explicitly otherwise stated), True (the properties should remain the same), False (the previous properties are ignored)) (DisplayFunction Function to apply to a graphic before returning it; default value: $DisplayFunction (is normally Identity)) The main difference between the options for the three commands is in the default value of BoxRatios: It is {1, 1, 0.4} for Plot3D and Automatic for ParametricPlot3D and Graphics3D. Note

that in the previous box, we do not mention the ControllerLinking, ControllerMethod, and ControllerPath options. ‡ Local Options

With Plot3D, ParametricPlot3D, and Graphics3D, the following options can be used to adjust some local components of a plot:

Chapter 7 • Graphics Options

213

An option for plot label: PlotLabel Label of the plot; examples of values: None, Sin[x y], "A surface plot" Options for axes and ticks: * Axes Whether to draw the axes; examples of values: True s p , False g , {True, True, False} AxesEdge Where to draw the axes; examples of values: Automatic, {{1,1}, {-1,1}, {1,1}}, { Automatic, {-1,1}, {1,1}}, {{1,1}, {-1,1}, None} * AxesLabel Labels for the axes; examples of values: None, z, {x, y}, {x, y, z} AxesStyle Style of the axes; examples of values: {}, Directive[Thick, Gray] * Ticks Ticks on the axes; simple examples of values: Automatic, None, {{0,1,2}, {0,1}, Automatic}, {{0,1,2}, {0,1}, {-1,0,1}} TicksStyle (Ÿ6) Style of tick marks and tick labels; examples of values: {}, Blue, Directive[Thick, Blue, 12]

Options for bounding box: * Boxed Whether to draw a bounding box around the surface; possible values: True, False * BoxRatios Ratios of side lengths of the bounding box; default values: {1, 1, 0.4} s , Automatic

pg

(BoxStyle Style of the bounding box; examples of values: {}, Directive[Thick, Gray]) Options for face grids: FaceGrids Grid lines drawn on the faces of the bounding box; examples of values: None, All, {{-1,0,0}, {0,1,0}, {0,0,-1}}, {{{-1,0,0}, {ygrid, zgrid}}, {{0,1,0}, {xgrid, zgrid}}, {{0,0,-1}, {xgrid, ygrid}}}

(FaceGridsStyle Style of the grid lines; examples of values: {}, Directive[Thick, Gray]) Options for primitives: (Prolog 2D graphics primitives to be plotted before the main plot; examples of values: {}, {PointSize[Medium], Red, Point[{0.4, 0.7}]}) Epilog 2D graphics primitives to be plotted after the main plot; examples of values: {}, {PointSize[Medium], Red, Point[{0.4, 0.7}]}

The main difference between the options for the three commands is in the default value of Axes: It is True for Plot3D and ParametricPlot3D and False for Graphics3D. ‡ Options for the Surface

With Plot3D and ParametricPlot3D, the following options can be used to adjust the surface to be plotted: Options for plot style: PlotStyle s p (Ÿ6) Style(s) of the surface(s); examples of values: Automatic, Yellow, Directive[Yellow, Specularity[Red, 5]], Opacity[0.3], None (BoundaryStyle s p (Ÿ6) How to draw boundary lines for surfaces; examples of values: Automatic s , None p , Thick) (ClippingStyle s (Ÿ6) How to draw clipped parts of the surface; examples of values: Automatic, None, Red, {Green, Red}) (NormalsFunction s p (Ÿ6) How to determine effective surface normals; default value: Automatic) Options for color function: ColorFunction s p What colors are used to color the surface, if simulated illumination is not used;

214

Mathematica Navigator examples of values: Automatic, GrayLevel, "Rainbow", (Hue[1 - #3] &), (RGBColor[#3, 1 - #3, 0] &)

(ColorFunctionScaling s p Whether values provided for a color function are scaled to lie between 0 and 1 (True) or left as such (False)) Options for filling: (Filling s (Ÿ6) Type of filling to use; examples of values: None, Axis, Bottom, Top, 0.3, True) (FillingStyle s (Ÿ6) Style of filling; examples of values: Opacity[0.5], Red) Options for mesh lines: sp How many mesh lines should be drawn; examples of values: Automatic, 10, {5, 10}, Full, All, {{0, 1, 2}, {1, 2}}, None MeshFunctions s p (Ÿ6) How to determine the placement of the mesh lines; examples of values: {#1 &, #2 &} s , Automatic p , {#3 &}, MeshStyle s p Style of mesh lines; examples of values: Automatic, Directive[Red, Thick] (MeshShading s p (Ÿ6) How to shade regions between mesh lines; examples of values: None, {{Red,Green}, {Green, Red}}) * Mesh

(Ÿ6) The curves on the Ix, yM surface that are excluded in plotting; examples of

Options for exclusions and region function: Exclusions

sp

values: Automatic, None, {x + y ã 0} (ExclusionsStyle s p (Ÿ6) What to draw at excluded curves; examples of values: None, Opacity[0.5], {Opacity[0.5], Directive[Red, Thick]}) RegionFunction s p (Ÿ6) Specifies the region to include in the plot drawn; examples of values: (True &), (#1^2 + #2^2 < 1 &) Options for plotting algorithm: PlotPoints s p Number of initial sampling points; examples of values: Automatic, 30, {30, 50} MaxRecursion s p (Ÿ6) The maximum number of recursive subdivisions allowed; examples of values: Automatic, 3 WorkingPrecision s p (Ÿ6) The precision used in computations; examples of values: MachinePrecision, 20 (PerformanceGoal s p (Ÿ6) What aspect of performance to try to optimize; examples of values: $PerformanceGoal, "Quality", "Speed") (EvaluationMonitor s p (Ÿ6) Expression to evaluate at every function evaluation; examples of values: None, Sow[{x, y, Sin[x y]}]) ‡ Example

First, we define the grid lines for x, y, and z:

xg = 8p ê 4, p ê 2, 3 p ê 4<; yg = 8p ê 4, p ê 2, 3 p ê 4<; zg = 80<;

In the plot, we color the surface with the ColorFunction option according to the height (to see the colors, look at the plot in the Help Browser if you have installed the CD-ROM of this book):

Chapter 7 • Graphics Options

215

[email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, BoxRatios Ø Automatic, Background Ø Black, PlotRegion Ø 880.05, 0.95<, 80.03, 0.95<<, ColorFunction Ø [email protected] - Ò3D &L, PlotPoints Ø 50, BaseStyle Ø 8FontFamily Ø "Helvetica"<, MeshStyle Ø Gray, MeshFunctions Ø HÒ3 &L, AxesLabel Ø 8x, y<, AxesStyle Ø [email protected], 9, BoldD, BoxStyle Ø White, Ticks Ø 880, 8p ê 2, "pê2"<, p<, 80, 8p ê 2, "pê2"<, p<, 8-1, 0, 1<<, FaceGrids Ø 888-1, 0, 0<, 8yg, zg<<, 880, 1, 0<, 8xg, zg<<, 880, 0, -1<, 8xg, yg<<<, PlotLabel Ø [email protected]@x yD [email protected], "Bold", 11, WhiteD, ImageSize Ø 250D êê Framed

7.5.2 Global Options ‡ Form and Size * BoxRatios Ratios of side lengths of the bounding box; default values: {1, 1, 0.4} s , Automatic p g

(AspectRatio Ratio of height to width of the plotting rectangle; default value: Automatic) ImageSize The absolute size (in printer’s points) of the plot; examples of values: Automatic, Full, All, width, {width, height}, {maxsize}, {{maxwidth}, {maxheight}} (Remember that options and values denoted by s, p, and g apply for Plot3D, ParametricPlot3D, and Graphics3D, respectively.) BoxRatios determines the form of the 3D bounding box. The default value {1, 1, 0.4} for Plot3D means that the x and y axes have the same length and that the z axis is 0.4 times this length. The default

value Automatic for ParametricPlot3D and Graphics3D tells us that one unit in all three axes has the same length. Thus, the setting BoxRatios Ø Automatic for 3D graphics corresponds to the setting AspectRatio Ø Automatic for 2D graphics.

216

Mathematica Navigator

[email protected]@x yD, 8x, 0, p<, 8y, 0, p<, BoxRatios Ø ÒD & êü 881, 1, 0.4<, Automatic, 81, 1, 1<<

:

,

,

>

and y axes has the same length to get the correct impression of the form of the Ix, yM region and setting

For surfaces produced by Plot3D, it may be worth setting the BoxRatios such that one unit on the x

the third component such that we get a good impression of the form of the surface. AspectRatio defines the 2D form of the plot. The default value Automatic leaves unchanged the form of the graphics determined by the BoxRatios option. AspectRatio is seldom used for 3D graphics. Instead, BoxRatios is the option for defining the 3D form of the surface.

For ImageSize, see Section 7.2.1, p. 189. ‡ Plot Range * PlotRange Ranges for x, y, and z in the plot; examples of values: Automatic g

,

{zmin,Automatic},

{Full, Full, Automatic} s ,

{zmin,All},

{Full, Full, All},

Full,

{All,zmax},

{{xmin, xmax}, {ymin, ymax}, All},

5,

{zmin,zmax},

{{xmin, xmax}, {ymin, ymax}, {zmin, zmax}}

All

,

p

The values in the first two columns specify the range for z only. The values in the third column also specify the ranges for x and y. The value Automatic determines the z range with an algorithm that may clip some high or low parts of the surface. Giving the value All ensures that the surface is wholly plotted without clipping. The value Full also causes the whole function to be plotted but, in addition, the whole plotting range on x and y axes is included in the plot. A constant value such as 5 means, for Plot3D, the plot range {Full, Full, {-5, 5}} and, for Graphics3D and ParametricPlot3D, the plot range {{-5, 5}, {-5, 5}, {-5, 5}}. In the first plot shown next, high values near the point H3, 3L are clipped: [email protected]@x yD, 8x, 0, 3<, 8y, 0, 3
:

,

>

Chapter 7 • Graphics Options

217

(ClippingStyle s (Ÿ6) How to draw clipped parts of the surface; examples of values: Automatic, None, Red, {Green, Red}) ‡ Margins and Background PlotRegion Specifies margins around the plot inside the selection rectangle; examples of values: Automatic (means {{0, 1}, {0, 1}}), {{xmin, xmax}, {ymin, ymax}} SphericalRegion Whether to leave room in the plotting rectangle for a sphere enclosing the

bounding box; possible values: False, True (ImageMargins Specifies margins (in printer’s points) outside the selection rectangle; examples of values: 0, Automatic, 15, {{left, right}, {bottom, top}}) (ImagePadding (Ÿ6) Extra space (in printer’s points) for objects such as thick lines and tick and axes labels; examples of values: All, None, 15, {{left, right}, {bottom, top}}) (PlotRangePadding (Ÿ6) How much farther axes etc. should extend beyond the range of coordinates specified by PlotRange; examples of values: Automatic, None, {0.2, 0.5}) Background Color of the background; examples of values: None, LightGray PlotRegion determines the 2D margins around the plot in the usual way, as it does for 2D graphics

(see Section 7.2.3, p. 191). The default value Automatic means {{0, 1}, {0, 1}}: The plot fills the entire display area. A value such as {{0.05, 0.95}, {0.05, 0.95}} leaves wider margins; this may be useful when using a colored background (see the example of Section 7.5.1, p. 214). SphericalRegion determines whether to leave room in the plotting rectangle for a sphere enclosing the bounding box. The value True is useful when rotating a graphic with animation because the graphic has the same size from all viewpoints (this is important in animation). ‡ Fonts and Formatting * BaseStyle (Ÿ6) Style of texts; examples of values: {}, {9, Bold, FontFamily Ø "Helvetica"} LabelStyle (Ÿ6) Style of all labels; examples of values: {}, {9, Bold, FontFamily Ø "Helvetica"}

(FormatType Format type of text used in a plot; examples of values: TraditionalForm, StandardForm, InputForm, OutputForm) For fonts and formatting, see Section 7.2.4, p. 192. ‡ Viewpoint and Lighting * ViewPoint Point (in a scaled coordinate system) from which the surface is viewed; default value: {1.3, -2.4, 2} RotationAction (Ÿ6) How to render the plot if rotated with the mouse; examples of values: "Fit"

(after rotation, the plot is rescaled to fit into the image region), "Clip" (after rotation, the plot is not rescaled and so may be clipped) (ViewAngle (Ÿ6) Angle of the field of view; default value: Automatic) (ViewCenter Point (in scaled coordinates) to display at the center; default value: {1/2, 1/2, 1/2}) (ViewMatrix (Ÿ6) Explicit transformation matrix; default value: Automatic) (ViewRange (Ÿ6) Range of viewing distances to include; default value: All) (ViewVector (Ÿ6) Position and direction of a simulated camera; default value: Automatic) (ViewVertical Direction to make vertical; default value: {0, 0, 1})

218

Mathematica Navigator

We plot the same surface from three different viewpoints:

[email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, ViewPoint Ø ÒD & êü 881.3, -2.4, 2<, 81.3, -2.4, 0<, 81.3, -2.4, -1<<

:

,

,

>

The viewpoint coordinates are not coordinates of the surface; the viewpoint has its own coordinate system. The origin of this system is at the center of the bounding box, and the longest side of the box runs from -0.5 to 0.5. The other sides then run so that the lengths of the sides satisfy the proportions expressed in BoxRatios. Thus, if we have BoxRatios Ø {1, 1, 0.4}, then the viewpoint coordinates of the box run from -0.5 to 0.5 for x and y and from -0.2 to 0.2 for z. The value of the ViewPoint option can also be one of Above, Below, Front, Back, Left, or Right. One of the coordinates can also be infinite, such as in {0, 0, ¶}. Recall from Section 5.3.1, p. 139, that we can rotate a 3D plot by dragging with the mouse so that we can easily see the surface from various viewpoints. A 3D plot can also be zoomed with the mouse by holding down the ‚ (Windows) or Ì (Macintosh) key and dragging upward (to zoom in) or downward (to zoom out). After rotating with the mouse, the plot is rescaled to fit into the image region. This causes a “jump” when the mouse is released. Give the RotationAction option the value "Clip" if you do not want the plot rescaled; now the plot may partly fall out of the image region and thus be clipped, or extra space may appear around the plot. The current viewpoint of a rotated plot can be seen by pasting the figure as the argument to Options:

ViewPoint ê. OptionsB

F

8-0.972355, 3.08212, 1.00253< Lighting What simulated lighting to use; simple examples of values: Automatic, "Neutral", None

The automatic lighting uses ambient light together with four light sources. Neutral lighting uses white light sources. If we use no lighting, the result is a black surface. For more about lighting, see the Documentation Center.

Chapter 7 • Graphics Options

219

[email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, Lighting Ø ÒD & êü 8Automatic, "Neutral", None<

:

,

,

>

‡ Miscellaneous Options

(BaselinePosition (Ÿ6) Where the baseline of a plot should be if the plot is combined with other plots or text; examples of values: Automatic, Axis, Bottom, Top, Center, Baseline) (AlignmentPoint (Ÿ6) How objects should by default be aligned when they appear in Inset; default value: Center) (ContentSelectable (Ÿ6) Whether and how content of a plot should be selectable; possible values: Automatic (double-click allows content selection), True (single clicks immediately select content objects), False (content objects cannot be selected)) (PreserveImageOptions (Ÿ6) Whether the size and margins of a plot should remain the same if the plotting command is executed anew; examples of values: Automatic (the properties should remain the same if not explicitly otherwise stated), True (the properties should remain the same), False (the previous properties are ignored)) (DisplayFunction Function to apply to a graphic before returning it; default value: $DisplayFunction (is normally Identity))

7.5.3 Local Options ‡ Plot Label PlotLabel Label of the plot; examples of values: None, Sin[x y], "A surface plot" PlotLabel was considered in Section 7.3.1, p. 195; there is also an example in Section 7.5.1, p. 214. ‡ Axes and Ticks

, False g , {True, True, False} AxesEdge Where to draw the axes; examples of values: Automatic, {{1,1}, {-1,1}, {1,1}}, { Automatic, {-1,1}, {1,1}}, {{1,1}, {-1,1}, None} * AxesLabel Labels for the axes; examples of values: None, z, {x, y}, {x, y, z} AxesStyle Style of the axes; examples of values: {}, Directive[Thick, Gray]

* Axes Whether to draw the axes; examples of values: True

sp

The default value of Axes is True for Plot3D and ParametricPlot3D and False for Graphics3D. If the plot has the bounding box, some edges of the box are selected as the axes. Note, however, that axes and the box can be drawn independently: You can have axes without the box, the box without the axes, or neither the axes nor the box; see forthcoming examples.

220

Mathematica Navigator

The edges of the box that are used as axes are, by default, determined automatically. However, each axis can be drawn on any of four edges with AxesEdge. In the next example, the first {-1, -1} defines the position of the x axis as the edge where y and z have the minimum values. {1, -1} defines the position of the y axis as the edge where x has the maximum value and z the minimum value. The last {-1, -1} defines the position of the z axis as the edge where x and y have the minimum values. (By the

way, these definitions are unnecessary in this example because they are the default definitions.) Any definition can also be Automatic (that axis is chosen automatically) or None (that axis is not drawn). * Ticks Ticks on the axes; simple examples of values: Automatic, None, {{0,1,2}, {0,1}, Automatic}, {{0,1,2}, {0,1}, {-1,0,1}} TicksStyle (Ÿ6) Style of tick marks and tick labels; examples of values: {}, Blue, Directive[Thick, Blue, 12] [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, AxesLabel Ø 8x, y, z<, AxesEdge Ø 88-1, -1<, 81, -1<, 8-1, -1<<, AxesStyle Ø [email protected], Ticks Ø 880, p<, 80, p<, 8-1, 1<
AxesLabel, AxesStyle, Ticks, and TicksStyle are used as they are with 2D plots (see Section 7.3.2,

p. 196). We have marked AxesLabel with an asterisk because in 3D plots, the labels are useful: It is not obvious which one of the two horizontal axes is the x axis and which is the y axis. ‡ Bounding Box * Boxed Whether to draw a bounding box around the surface; possible values: True, False * BoxRatios Ratios of side lengths of the bounding box; default values: {1, 1, 0.4} s , Automatic

pg

(BoxStyle Style of the bounding box; examples of values: {}, Directive[Thick, Gray]) BoxRatios was considered in Section 7.5.2, p. 215. For example,

p1 = [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø 880, p<, 80, p<, 8-1, 1<
:

,

,

>

Chapter 7 • Graphics Options

221

‡ Face Grids FaceGrids Grid lines drawn on the faces of the bounding box; examples of values: None, All, {{-1,0,0}, {0,1,0}, {0,0,-1}}, {{{-1,0,0}, {ygrid, zgrid}}, {{0,1,0}, {xgrid, zgrid}}, {{0,0,-1}, {xgrid, ygrid}}}

(FaceGridsStyle Style of the grid lines; examples of values: {}, Directive[Thick, Gray]) The value All draws grids on all six faces. We can define the faces where we want the grids. For example, {-1,0,0} is the face where x has the smallest value, {0,1,0} is the face where y has the largest value, and {0,0,-1} is the face where z has the smallest value. The example in Section 7.5.1, p. 214, contains grid lines. ‡ Primitives

(Prolog 2D graphics primitives to be plotted before the main plot; examples of values: {}, {PointSize[Medium], Red, Point[{0.4, 0.7}]}) Epilog 2D graphics primitives to be plotted after the main plot; examples of values: {}, {PointSize[Medium], Red, Point[{0.4, 0.7}]}

For Prolog and Epilog, we refer to Section 7.3.6, p. 201. These options can be used to add 2D graphics primitives to the plot. Note that the primitives cannot be 3D. In addition, the coordinates used in the primitives have to be given with scaled coordinates, which run from 0 to 1 in both horizontal and vertical directions. If you want to add 3D primitives (see Section 6.2.11, p. 176), plot the primitives with Graphics3D and then use Show to combine the main plot and the primitives. For example,

p1 = [email protected]@sD H3 + [email protected], [email protected], [email protected] H3 + [email protected]<, 8s, 0, 2 p<, 8t, 0, 2 p<, Boxed Ø False, Axes Ø FalseD;

p2 = [email protected], [email protected], 0, 0<, 85, 0, 0<
222

Mathematica Navigator

7.5.4 Options for the Surface ‡ Plot Style PlotStyle

sp

(Ÿ6) Style(s) of the surface(s); examples of values: Automatic, Yellow,

Directive[Yellow, Specularity[Red, 5]], Opacity[0.3], None

(BoundaryStyle

sp

(Ÿ6) How to draw boundary lines for surfaces; examples of values: p , Thick) s (ClippingStyle (Ÿ6) How to draw clipped parts of the surface; examples of values: Automatic, None, Red, {Green, Red}) (NormalsFunction s p (Ÿ6) How to determine effective surface normals; default value: Automatic) s

Automatic , None

With PlotStyle, we can change the colors of a surface:

[email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, ImageSize Ø 90, PlotStyle Ø ÒD & êü 8Automatic, Yellow, [email protected], None<

:

,

,

,

>

The default value Automatic for ClippingStyle produces plateaus at the top and bottom of the surface. The plateaus have no mesh lines; see the first plot shown next. The value None leaves the clipped parts empty, and this reveals the clipped parts very clearly; see the second plot. The clipped parts can also be shown with colors; see the third and fourth plots. [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, PlotRange Ø 8-0.7, 0.85<, ImageSize Ø 90, ClippingStyle Ø ÒD & êü 8Automatic, None, Red, 8Green, Red<<

:

,

,

,

>

‡ Color Function sp

What colors are used to color the surface, if simulated illumination is not used; examples of values: Automatic, GrayLevel, "Rainbow", (Hue[1 - #3] &), (RGBColor[#3, 1 - #3,

ColorFunction 0] &)

(ColorFunctionScaling s p Whether values provided for a color function are scaled to lie between 0 and 1 (True) or left as such (False)) Instead of simulated illumination, we can use a color function to color the surface. The function is expressed as a pure function (for pure functions, see Section 2.2.2, p. 38). In the function, we can use #1, #2, and #3 to denote the x, y, and z coordinates, respectively. In a parametric surface, we can also use #4

and #5 to denote the parameters u and v, respectively. A useful coloring is obtained by coloring according to the value of z:

Chapter 7 • Graphics Options

223

[email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, ColorFunction Ø ÒD & êü 8Automatic, GrayLevel, "Rainbow"<

:

,

>

,

[email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, ColorFunction Ø [email protected] - Ò3D &LD, [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, ColorFunction Ø [email protected]Ò3, 1 - Ò3, 0D &LD, [email protected] [email protected] [email protected], s [email protected] [email protected], -s [email protected]<, 8s, 0, 2 p<, 8t, 0, p<, Mesh Ø False, ColorFunction Ø [email protected]Ò4 Ò5D &L, Boxed Ø False, Axes Ø FalseD<

:

,

,

>

Here, we used the special color function "Rainbow". To see a list of other color functions, execute ColorData["Gradients"]. For ColorData, see Section 9.3.3, p. 304. ‡ Filling

(Filling s (Ÿ6) Type of filling to use; examples of values: None, Axis, Bottom, Top, 0.3, True) (FillingStyle s (Ÿ6) Style of filling; examples of values: Opacity[0.5], Red) Filling may be useful in connection with RegionFunction to make an unusual plotting region

clearer:

[email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, Filling Ø BottomD, [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, Filling Ø Bottom, RegionFunction Ø HHÒ1 - p ê 2L ^ 2 + HÒ2 - p ê 2L ^ 2 § Hp ê 2L ^ 2 &LD<

:

,

>

224

Mathematica Navigator

‡ Mesh Lines * Mesh

sp

How many mesh lines should be drawn; examples of values: Automatic, 10, {5, 10},

Full, All, {{0, 1, 2}, {1, 2}}, None sp

(Ÿ6) How to determine the placement of the mesh lines; examples of values: {#1 p , {#3 &} sp Style of mesh lines; examples of values: Automatic, Directive[Red, Thick] MeshStyle (MeshShading s p (Ÿ6) How to shade regions between mesh lines; examples of values: None, {{Red,Green}, {Green, Red}}) MeshFunctions s

&, #2 &} , Automatic

If the value of Mesh is Full, we get the initial sampling mesh. Value All gives the final sampling mesh. [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, Mesh Ø ÒD & êü 8Full, All, None<

:

,

,

>

By defining the mesh function to be the z value, we can draw a combined surface and contour plot, as is shown in the first plot below. [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, MeshFunctions Ø 8Ò3 &<, Mesh Ø [email protected], 0.9, 0.2D
:

,

,

>

Next, we see three norm functions. Each plot contains a mesh curve where the norm gets the value 1:

Chapter 7 • Graphics Options

225

[email protected]@8x, y<, ÒD, 8x, -1.5, 1.5<, 8y, -1.5, 1.5<, PlotRange Ø 80, 3<, MeshFunctions Ø 8Ò3 &<, Mesh Ø 881<<, BoxRatios Ø Automatic, ViewPoint Ø 81.1, -2.3, 2.4
:

,

,

>

‡ Exclusions and Region Function Exclusions

sp

(Ÿ6) The curves on the Ix, yM surface that are excluded in plotting; examples of

values: Automatic, None, {x + y ã 0} (ExclusionsStyle s p (Ÿ6) What to draw at excluded curves; examples of values: None, Opacity[0.5], {Opacity[0.5], Directive[Red, Thick]}) The default is that nothing is drawn at excluded curves, as can be seen from the first plot shown next. In the second plot, we ask not to exclude anything. In the third plot, we use a custom style to indicate the exclusions. In the fourth plot, we use a special style for the boundary of the surface at the excluded curve. [email protected]@[email protected]@x + I yDD, 8x, -1, 1<, 8y, -1, 1<, Ticks Ø NoneD, [email protected]@[email protected] + I yDD, 8x, -1, 1<, 8y, -1, 1<, Ticks Ø None, Exclusions Ø NoneD, [email protected]@[email protected] + I yDD, 8x, -1, 1<, 8y, -1, 1<, Ticks Ø None, ExclusionsStyle Ø [email protected], [email protected]@[email protected] + I yDD, 8x, -1, 1<, 8y, -1, 1<, Ticks Ø None, ExclusionsStyle Ø 8None, [email protected], ThickD
Exclusions can be defined with equations:

226

Mathematica Navigator

[email protected] ê Hx + yL ^ 3, 8x, -1, 1<, 8y, -1, 1<, Ticks Ø NoneD, [email protected] ê Hx + yL ^ 3, 8x, -1, 1<, 8y, -1, 1<, Ticks Ø None, Exclusions Ø 8x + y ã 0
:

,

RegionFunction

sp

>

(Ÿ6) Specifies the region to include in the plot drawn; examples of values:

(True &), (#1^2 + #2^2 < 1 &)

With RegionFunction, we can show a surface at a region defined by a logical combination of inequalities: [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, Ticks Ø None, RegionFunction Ø HHp ê 3L ^ 2 < HÒ1 - p ê 2L ^ 2 + HÒ2 - p ê 2L ^ 2 § Hp ê 2L ^ 2 &LD

‡ Plotting Algorithm sp

Number of initial sampling points; examples of values: Automatic, 30, {30, 50} (Ÿ6) The maximum number of recursive subdivisions allowed; examples of values: Automatic, 3 WorkingPrecision s p (Ÿ6) The precision used in computations; examples of values: MachinePrecision, 20 (PerformanceGoal s p (Ÿ6) What aspect of performance to try to optimize; examples of values: $PerformanceGoal, "Quality", "Speed") (EvaluationMonitor s p (Ÿ6) Expression to evaluate at every function evaluation; examples of values: None, Sow[{x, y, Sin[x y]}])

PlotPoints

MaxRecursion

sp

7.6 Options for Contour and Density Plots 7.6.1 Special Options Contour and density plots describe 3D functions, but the plots are like 2D plots. Indeed, most options and their default values of these commands are the same as those of Plot. Thus, we can mainly refer to Sections 7.1 through 7.4 for the options. Here, it may suffice to mention the differences between the default values of a few options and some new options of ContourPlot.

Chapter 7 • Graphics Options

227

‡ Aspect Ratio

The default value of AspectRatio is 1/GoldenRatio for Plot but 1 for ContourPlot and DensityPlot. Thus, the form of a contour or density plot is, by default, a square. If you want one unit in the x and y axes to have the same length, give the value Automatic for this option. ‡ Plot Range

Note that the value of PlotRange in a contour or density plot is given as for Plot3D. Remember that high or low z values may be clipped. In a contour or density plot, the clipped parts appear as white or dark blue regions and may easily remain unobserved. Use PlotRange Ø All to see all z values: [email protected]@x yD, 8x, 0, 1.5<, 8y, 0, 1.5
:

,

>

‡ Axes, Frame, and Ticks

A contour or density plot has, by default, a frame and no axes. Thus, ticks are set with FrameTicks and not with Ticks, and x and y labels are set with FrameLabel and not with AxesLabel. If the y label is short, the rotating of the label should be avoided by setting RotateLabel Ø False. Axes can be useful either in addition to the frame or in place of the frame: 8p1 = [email protected] ^ 4 - 3 x ^ 2 y - 5 y ^ 2 - x - y, 8x, -1.6, 0.6<, 8y, -1.1, 0.6<, AspectRatio Ø Automatic, PlotRange Ø All, Contours Ø 24D, [email protected], Axes Ø TrueD, [email protected], Axes Ø True, Frame Ø FalseD<

:

,

,

>

‡ Color Function ColorFunction How to color the regions between the contour lines (ContourPlot) or how to color

various values of the function (DensityPlot); examples of values: Automatic, GrayLevel, "Rainbow", (Hue[1 - #] &), (RGBColor[#, 0, 1 - #] &) (ColorFunctionScaling Whether values provided for a color function are scaled to lie between 0 and 1 (True) or left as such (False))

228

Mathematica Navigator

ContourPlot and DensityPlot do not have the PlotStyle option. Instead, we can use the ColorFunction option:

[email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, ColorFunction Ø ÒD & êü 8Automatic, GrayLevel, [email protected]Ò, 0, 1 - ÒD &L<

:

,

,

>

[email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, ColorFunction Ø ÒD & êü 8GrayLevel, [email protected]Ò, 0, 1 - ÒD &L, [email protected] H1 - ÒLD &L<

:

,

,

>

From the last density plot we can see that the colors are not smooth enough. A setting of, for example, PlotPoints Ø 50 would give a good result. As an aside, from the first density plot I get the strong impression of a surface seen above and lighted from northeast, but this interpretation is wrong: The gray parts are not shadows but instead describe deep parts of the surface. ContourPlot and DensityPlot have the BoundaryStyle option (with default value None) to define the style of the boundary of the plotted region. ‡ Special Options of ContourPlot * Contours Number of z values for which contour lines are to be drawn or a list of z values;

examples of values: Automatic, 10, {-2, -1, 0, 1, 2} * ContourLines Whether to draw the contour lines; possible values: True, False ContourStyle Style of the contour lines; examples of values: Automatic, Black ContourLabels (Ÿ6) How to label contour lines; examples of values: None, Automatic * ContourShading How to shade regions between the contour lines; examples of values: Automatic, True, False

In the first plot that follows, we ask for five equally paced contours, whereas in the second plot we define the contours explicitly. In the third plot, we ask not to draw the contour lines.

Chapter 7 • Graphics Options

229

[email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, Contours Ø 5D, [email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, Contours Ø [email protected], 1, 0.25DD, [email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, ContourLines Ø FalseD< 3.0 2.5 2.0

:

,

,

>

1.5 1.0 0.5 0.0 0.0

0.5

1.0

1.5

2.0

2.5

3.0

In the first plot that follows, we define black to be the style of the contours. In the second plot, we ask to label the contours. In the third plot, we ask not to use shading between the contour lines. [email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, ContourStyle Ø BlackD, [email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, ContourLabels Ø AutomaticD, [email protected]@x yD [email protected], 8x, 0, p<, 8y, 0, p<, ContourShading -> FalseD< 3.0 2.5 2.0

: 1.5

,

,

>

1.0 0.5 0.0 0.0

0.5

1.0

1.5

2.0

2.5

3.0

Remember that by moving the mouse pointer over a contour plot (without pressing the mouse button), we can see the constants corresponding to the contours. Using evenly spaced contours, it may sometimes be difficult to get a good description of a function, even with a large number of contours. The value of the Contours option can also be a function of the minimum and maximum values of the function, and with such a function we can get better contours: [email protected] - 1L ^ 2 + 100 Hy - x ^ 2L ^ 2, 8x, -1, 1<, 8y, -1, 1<, ContourShading Ø False, Contours Ø 30, PlotRange Ø AllD, [email protected] - 1L ^ 2 + 100 Hy - x ^ 2L ^ 2, 8x, -1, 1<, 8y, -1, 1<, ContourShading Ø False, PlotRange Ø All, Contours Ø [email protected], max<, [email protected]@0, [email protected], [email protected] ê 10DDDD<

:

,

>

230

Mathematica Navigator

‡ Example

For the following plot, we use several options to enhance it. f = -x ^ 4 - 3 x ^ 2 y - 5 y ^ 2 - x - y; p = 8x, y< ê. [email protected], 8x, 0<, 8y, 0
[email protected], 8x, -1.3, 0.1<, 8y, -0.8, 0.1<, Contours Ø 19, AspectRatio Ø Automatic, PlotRegion Ø 880.01, 0.94<, 80.04, 0.96<<, Background Ø Black, BaseStyle Ø 810, White<, ColorFunction Ø "Rainbow", PlotLabel Ø [email protected] ^ 4 - 3 x ^ 2 y - 5 y ^ 2 - x - y, Bold, 14D, FrameTicks Ø 88pP1T, 0<, 8pP2T, 0<, None, None<, FrameStyle Ø [email protected], ImageSize Ø 400, Epilog Ø [email protected], [email protected], [email protected]"Maximum point", p, 8-1.1, -1.4
8 Graphics for Data Introduction 231 8.1 Basic Plots 232 8.1.1 Built-in Plots 232 ListPlot, ListLinePlot, ListLogPlot, ErrorListPlot, DateListPlot, etc. 8.1.2 Self-Made Plots 238 Graphics 8.1.3 Plots of Several Data Sets 242 ListPlot, ListLinePlot, Graphics 8.2 Scatter Plots 249 8.2.1 Scatter Plots 249 ListPlot, PairwiseScatterPlot 8.2.2 Quantile-Quantile Plots 252 QuantilePlot 8.3 Bar Charts 253 8.3.1 Bar Charts 253 BarChart, StackedBarChart, GeneralizedBarChart, etc. 8.3.2 Histograms 258 Histogram 8.3.3 Stem-and-Leaf Plots 259 StemLeafPlot 8.4 Other Plots 260 8.4.1 Dot Plots 260 dotPlot 8.4.2 Box-and-Whisker Plots 264 BoxWhiskerPlot 8.4.3 Pie Charts 266 PieChart 8.4.4 Vector Fields 266 ListVectorFieldPlot 8.5 Graph Plots 267 8.5.1 Graph Plots 267 GraphPlot, LayeredGraphPlot 8.5.2 Tree Plots 274 TreePlot 8.6 Plots for 3D Data 275 8.6.1 Plots for 3D Data 275 ListPlot3D, BarChart3D, ListDensityPlot, ListContourPlot, etc.

Introduction “Data! data! data!” he cried impatiently. “I can’t make bricks without clay.”~Sherlock Holmes In this chapter, we present ways to illustrate data with 2D and 3D graphics. A basic situation encountered when plotting data is one or more time series: data sets with one dependent variable and time as the independent variable. Plotting such data is considered in Section 8.1. The basic commands are ListPlot and ListLinePlot, but we can also easily use Graphics. When we want to study the relationships between two or more dependent variables, the scatter plot methods of Section 8.2 are useful. The basic approach, with ListPlot or PairwiseScatterPlot, is to plot one variable against another variable, thereby yielding a scatter plot or, more generally, a scatter plot matrix. This method of pairing observations is also used in quantile-quantile plots.

232

Mathematica Navigator

Other plotting commands for data include BarChart, Histograms, dotPlot, BoxWhiskerPlot, and PieChart. These are considered in Sections 8.3 and 8.4. New in Mathematica 6 are GraphPlot, LayeredGraphPlot, and TreePlot; they are addressed in Section 8.5.

For 3D graphics, ListPlot3D, ListContourPlot, and ListDensityPlot make up one collection of commands to be tried. An effective plot may be a 3D bar chart done with BarChart3D. Also, a scatter plot made with ListPointPlot3D may sometimes be effective. In Chapter 9, we consider the data sets that come with Mathematica. There, we use some of the plotting methods presented here. The data sets also contain some original graphics such as chemical diagrams, photos of astronomical objects, shapes of countries, flags, polyhedrons, graphs, lattices, knots, and various test images. Chapters 10 and 11 contain some manipulations of data. For example, we show how to interactively and graphically study interpolation and approximation.

8.1 Basic Plots 8.1.1 Built-in Plots ‡ Basic Plots ListPlot[data] Plot points ListLinePlot[data] (Ÿ6) Plot joining lines ListLinePlot[data, Mesh Ø All] Plot joining lines and points ListPlot[data, Filling Ø Axis] Plot points and vertical lines (stems) ListLinePlot[data, Filling Ø Axis] Plot joining lines; fill area below the curve ListLinePlot[data, Mesh Ø All, Filling Ø Axis] Plot joining lines and points; fill area below

the curve Data can be given in either of the following forms: {y1 , y2 , … } Plot the points {1, y1 }, {2, y2 }, … {{x1 , y1 }, {x2 , y2 }, … } Plot the given points

Instead of ListLinePlot[data], we can apply ListPlot[data, Joined Ø True]. As an example, we plot 30 random numbers in all six ways: [email protected]; data = [email protected], 0.2 x + 2 [email protected]<, 8x, 0, 30
7

7

6

6

5

5

4

,

5

10

15

20

25

30

>

4

,

3

3

2

2

1

1 5

10

15

20

25

30

5

10

15

20

25

30

Chapter 8 • Graphics for Data

233

[email protected], Filling Ø AxisD, [email protected], Filling Ø AxisD, [email protected], Mesh Ø All, Filling Ø AxisD<

:

,

,

>

The first of these six plots shows clearly the points and the second plot shows the path, but the third shows clearly both the points and the path. The plots in the second row make the data somewhat more concrete with the vertical lines or fills. A plot with vertical lines is able to clearly reveal possible lacking observations because the lacking lines will be so remarkable. A plot with a fill makes the shape of the curve very clear. ‡ Defining Styles

Defining styles in ListPlot: PlotStyle Style of points FillingStyle (Ÿ6) Style of vertical lines Defining styles in ListLinePlot: PlotStyle Style of joining lines MeshStyle Style of points FillingStyle (Ÿ6) Style of fills A single style such as Red can be written as such, but several styles need either braces or Directive (see Section 7.1.2, p. 188). The default size of points is AbsolutePointSize[3], and the default thickness of lines is AbsoluteThickness[0.5]. The default color is Hue[0.67, 0.6, 0.6] (a modified blue); in vertical lines,

this color is modified with Opacity[0.2] (thus, the blue color is very transparent and light). Remember that we considered the styles of points and lines in Sections 6.2.1, p. 155, and 6.2.2, p. 156. Styles are defined with so-called style directives. The following is a summary: • For colors, we have directives such as Hue, RGBColor, GrayLevel, and Opacity; for some colors, we also have ready-to-use names such as Red or LightBlue. •Point size can be defined with PointSize or AbsolutePointSize. •Thickness of lines can be defined with Thickness or AbsoluteThickness; we also have special thickness definitions Thin and Thick. •Dashing of lines can be defined with Dashing or AbsoluteDashing; we also have special dashing definitions Dotted, Dashed, and DotDashed. •The argument of the directives defining point size, thickness, or dashing can also be one of the special symbols Tiny, Small, Medium, or Large.

234

Mathematica Navigator

‡ Examples

Here are some examples of using styles in ListPlot and ListLinePlot:

[email protected], PlotStyle Ø [email protected], [email protected], [email protected], PlotStyle Ø [email protected], [email protected], [email protected], PlotStyle Ø [email protected], ThinD, Mesh Ø All, MeshStyle Ø [email protected], [email protected]< 7 6 5 4 :3 2 1

7

7

6

6

5

5

4

,

3 2

10

15

20

25

30

3 2

1 5

>

4

,

1 5

10

15

20

25

30

5

10

[email protected], PlotStyle Ø [email protected], [email protected], Filling Ø Axis, FillingStyle Ø [email protected], [email protected], [email protected], PlotStyle Ø [email protected], [email protected], Filling Ø Axis, FillingStyle Ø [email protected], 0.6DD, [email protected], PlotStyle Ø [email protected], ThinD, Mesh Ø All, MeshStyle Ø [email protected], [email protected], Filling Ø Axis, FillingStyle Ø [email protected]@0.3D, BlueDD< 7

7

6

6

5

5

:3 4

4

,

2

1

1 5

10

15

20

25

30

,

3

2

5

10

15

20

25

15

20

25

30

>

30

If the data contain both negative and positive values, we can define a different filling style for the negative and positive values: [email protected]@8x, -4 + 0.2 x + 2 [email protected]<, 8x, 0, 30
5

10

15

20

25

30

‡ Options

The options and their default values for ListPlot are mostly the same as for Plot. However, ListPlot has five options that Plot does not have. On the other hand, ListPlot does not have some options (e.g., PlotPoints and MaxRecursion) of Plot that control the sampling of the function to be plotted. The options of ListPlot and ListLinePlot are otherwise the same, but the default value of Joined is False for ListPlot and True for ListLinePlot. Thus, we can mainly refer to Chapter 7 for the options of ListPlot and ListLinePlot. However, here are the five options that Plot does not have.

Chapter 8 • Graphics for Data

235

DataRange The range of x values to assume; examples of values: Automatic, {0, 1} InterpolationOrder The degree of the polynomials joining the points; examples of values: None, 0, 1, 2, 3 Joined (Ÿ6) Whether to join the points; possible values: False (the default for ListPlot), True (the

default for ListLinePlot) MaxPlotPoints The maximum number of points plotted; examples of values: ¶, 100 PlotMarkers (Ÿ6) Markers to use for the points; examples of values: None, Automatic

In our previous examples, we had points with both x and y coordinates. If the data do not contain the x coordinates, the x coordinates 1, 2, … are used. If we want to determine the x coordinates, we can either add the coordinates to the data or use the DataRange option. Here are data without the x coordinates: [email protected]; data2 = [email protected] x + 2 [email protected], 8x, 0, 30
If we plot these data as such, the x coordinates will be 1, …, 31, not 0, …, 30. However, we can add the x coordinates: data3 = [email protected], 30D, data2<¨;

(Here,  means transpose; it can be written as ÂtrÂ.) We can also use the DataRange option: [email protected], [email protected], DataRange Ø 80, 30
7 6 5 4 :3 2 1

6 5

>

4

,

3 2 1

5

10

15

20

25

30

5

10

15

20

25

30

With the InterpolationOrder option we can get piecewise constant, linear (the default), etc. curves between the points. With the value 3, we get third-order spline interpolation: t = [email protected], 6<, 820
84, 6, 3, 2, 1, 3, 1, 6, 5, 1, 1, 6, 5, 1, 1, 4, 1, 2, 3, 4<

[email protected], InterpolationOrder Ø Ò, Mesh Ø FullD & êü 80, 1, 3<

:

6

6

5

5

4

4

,

3 2

6 5

10

15

20

3 2

2 5

>

4

,

3

1 5

10

15

20

5

10

15

20

For large data sets, the MaxPlotPoints option may be used to reduce the number of points plotted. The PlotMarkers option is useful in plotting several data sets, and so it is considered in Section 8.1.3, p. 244.

236

Mathematica Navigator

‡ Tooltips Tooltip[data] (Ÿ6) Show the coordinates of data as a tooltip when the mouse pointer is moved

over the points of data Tooltip[{xi, yi}, label] Show label as a tooltip for point {xi, yi}

In the following plot, we can see the coordinates of a point if we move the mouse pointer over that point: [email protected]@dataD, Mesh Ø AllD

In the next plot, we can see labels of the form f @kD when we move the mouse pointer over the points: dist = [email protected], 1 ê 2D; t = [email protected]@8k, [email protected], kD<, [email protected], 8k, 0, 20
‡ Example

Generate 100 random points on the unit square:

[email protected]; xy = [email protected], 8100, 2
The task is to visit all of the points once in such a way that the length of the tour is the minimum. With the following command, we can try to solve this problem: tour = [email protected]

87.86367, 81, 16, 39, 32, 59, 68, 6, 96, 75, 29, 80, 19, 85, 38, 78, 21, 65, 92, 97, 57, 52, 53, 84, 17, 7, 70, 83, 89, 88, 26, 11, 47, 5, 95, 86, 79, 82, 30, 93, 48, 9, 77, 94, 55, 71, 10, 12, 41, 27, 31, 2, 22, 58, 14, 99, 91, 42, 64, 36, 33, 72, 50, 28, 69, 45, 40, 87, 60, 15, 25, 63, 34, 67, 13, 61, 20, 24, 4, 43, 46, 51, 23, 54, 100, 62, 98, 90, 8, 74, 56, 18, 66, 73, 44, 81, 76, 3, 35, 37, 49<<

The length of the tour find is 7.86. The tour goes through the 1st, 16th, …, 49th point. We show both the points and the (at least near optimal) tour:

Chapter 8 • Graphics for Data

237

[email protected], AspectRatio Ø 1D, [email protected] êê LastT, Mesh Ø All, AspectRatio Ø 1D<

:

1.0

1.0

0.8

0.8

0.6

>

0.6

, 0.4

0.4

0.2

0.2

0.2

0.4

0.6

0.8

1.0

0.2

0.4

0.6

0.8

1.0

‡ Other Plots ListLogPlot[data] (Ÿ6) A plot of Log[yi] as a function of xi ListLogLinearPlot[data] (Ÿ6) A plot of yi as a function of Log[xi] ListLogLogPlot[data] (Ÿ6) A plot of Log[yi] as a function of Log[xi]

The data are given in the same form as they are for ListPlot. The option Joined can be used. In a logarithmic scale, exponential data are close to a line: [email protected]; data = [email protected], [email protected] + [email protected], 0.5
1.0

1.5

2.0

In the ErrorBarPlots` package: ErrorListPlot[data] Show data by points with error bars

Examples of data forms: {{y1 , yerr1 }, … } {{x1 , y1 , yerr1 }, … }

{{{x1 , y1 }, [email protected] , poserr1
In the first two data forms, the error is shown by a vertical bar centered at {xi , yi } and having a total length of two times the given error. In the third data form, there are different errors in the negative and positive directions. For example, data = [email protected] 8x, 1.5 + [email protected] + [email protected], 0.2
238

Mathematica Navigator

[email protected], AspectRatio Ø 0.4, PlotRange Ø All, AxesOrigin Ø 80, 0<, ImageSize Ø 230D 2.5 2.0 1.5 1.0 0.5 1

2

3

4

5

6

7

DateListPlot[{{date1 , y1 }, … }] (Ÿ6) Plot points with dates as x coordinates

To try this command, let us examine financial data; see Section 9.2.2, p. 299. The stock price of ADY from January 3, 2005, on has been as follows:

[email protected]"ADY", "Jan. 3, 2005"D êê Short

8882005, 1, 3<, 4.61<, 882005, 1, 4<, 4.59<, á937à, 882008, 9, 25<, 9.75<<

Here is a plot of the price until now: [email protected]@"ADY", "Jan. 1, 2005"D, ImageSize Ø 160, PlotStyle Ø [email protected] 25 20 15 10 5 2005

2006

2007

2008

Look at the Documentation Center for more information about DateListPlot. ListPolarPlot[radii] (Ÿ6) Plot points equally spaced in angle at radii

8.1.2 Self-Made Plots ‡ Using Graphics

We have ListPlot and ListLinePlot to plot data. However, it is very easy to plot data directly with the graphics primitives Point and Line (see Sections 6.2.1, p. 155, and 6.2.2, p. 156). With Graphics we collect the primitives together and show the resulting plot (see Section 6.1.1, p. 153). Here are ways to prepare four kinds of plots we encountered previously plus a plot where the points are shown as circles. Graphics[Point[data]] Points Graphics[Line[data]] Joining lines Graphics[{Line[data], Point[data]}] Joining lines and points Graphics[{ Line[{{#P1T, 0}, #}] & /@ data, Point[data]}] Vertical lines and points Graphics[{Line[data], White, EdgeForm[Black], Disk[#, Offset[{1.5, 1.5}]] & /@ data}] Joining lines and circles

Chapter 8 • Graphics for Data

239

These commands require that the data points contain both the x and the y coordinate. We can add some directives into the commands to get suitable styles for the plots. Also, we have to add the options Axes Ø True and AspectRatio Ø 1/GoldenRatio to get similar plots as we get with ListPlot and ListLinePlot (remember that Graphics has, by default, Axes Ø False and AspectRatio Ø Automatic). In the following, we first save the default values of the options of Graphics and then set some options with SetOptions: gropts = [email protected]; [email protected], Axes Ø True, AspectRatio Ø 1 ê GoldenRatio, AxesOrigin Ø 80, 0
Now we try using Graphics:

[email protected]; data = [email protected], 0.2 x + 2 [email protected]<, 8x, 0, 30
,

5

10

15

20

25

7 6 5 4 3 2 1

30

>

5

10

15

20

25

30

[email protected] 8Blue, [email protected], [email protected], Red, [email protected], [email protected]
,

5

10

15

20

25

7 6 5 4 3 2 1

30

>

5

10

15

20

25

30

Similarly, we can plot the data with circles [circles are popular in scientific publications; for example, Cleveland (1993) mainly uses circles]. If we used Circle, then the joining lines could be seen inside the circles, which is not beautiful. Therefore, we use Disk because it has a filled inside (see Section 6.2.7, p. 166). In the following example, we define the disks to be white with red edges: [email protected], [email protected], White, [email protected], [email protected]
10

15

20

25

30

Here we expressed the radius of the disks with Offset to get true circles and not ellipses.

240

Mathematica Navigator

‡ An Example

In this example, we consider the numbers of hare pelts sold to the Hudson Bay Trading Company in Canada from 1844 to 1934. These observations are from Burghes and Borrie (1981) (reproduced with the permission of the authors). First, we read the numbers of hare pelts from a file. I have the data in a text file called hare in a folder called MNData: haredata = [email protected]"êUsersêheikkiêDocumentsêMNDataêhare", "Table"D 881844, 81852, 81858, 81864, 81871, 81877, 81883, 81889, 81895, 81902, 81911, 81917, 81923, 81929,

30<, 81845, 25<, 81847, 25<, 81848, 15<, 81849, 30<, 81850, 55<, 81851, 80<, 80<, 81853, 90<, 81854, 70<, 81855, 80<, 81856, 95<, 81857, 75<, 30<, 81859, 15<, 81860, 20<, 81861, 40<, 81862, 5<, 81863, 155<, 140<, 81865, 105<, 81866, 45<, 81867, 20<, 81868, 5<, 81869, 5<, 81870, 10<, 10<, 81872, 60<, 81873, 50<, 81874, 50<, 81875, 105<, 81876, 85<, 60<, 81878, 15<, 81879, 10<, 81880, 15<, 81881, 10<, 81882, 10<, 40<, 81884, 50<, 81885, 135<, 81886, 135<, 81887, 90<, 81888, 30<, 20<, 81890, 50<, 81891, 55<, 81892, 60<, 81893, 55<, 81894, 80<, 95<, 81896, 50<, 81897, 15<, 81898, 5<, 81899, 5<, 81900, 15<, 81901, 5<, 10<, 81903, 50<, 81904, 70<, 81906, 20<, 81909, 25<, 81910, 50<, 55<, 81912, 75<, 81913, 70<, 81914, 55<, 81915, 30<, 81916, 20<, 15<, 81918, 15<, 81919, 20<, 81920, 35<, 81921, 60<, 81922, 80<, 85<, 81924, 60<, 81925, 30<, 81926, 20<, 81927, 10<, 81928, 5<, 5<, 81930, 10<, 81931, 30<, 81932, 80<, 81933, 100<, 81934, 80<<

The file hare can be found on the CD-ROM that comes with this book. For Import, see Section 4.2.1, p. 100. The numbers are in thousands and are quoted to the nearest 5000. Observations regarding the number of hare pelts are lacking for the years 1846, 1905, 1907, and 1908. We take the last 31 data points: hdata = [email protected], -31D 881901, 81911, 81917, 81923, 81929,

5<, 81902, 10<, 81903, 50<, 81904, 70<, 81906, 20<, 81909, 25<, 81910, 50<, 55<, 81912, 75<, 81913, 70<, 81914, 55<, 81915, 30<, 81916, 20<, 15<, 81918, 15<, 81919, 20<, 81920, 35<, 81921, 60<, 81922, 80<, 85<, 81924, 60<, 81925, 30<, 81926, 20<, 81927, 10<, 81928, 5<, 5<, 81930, 10<, 81931, 30<, 81932, 80<, 81933, 100<, 81934, 80<<

Here are the data plotted in eight ways: [email protected], Axes Ø True, AspectRatio Ø 1 ê GoldenRatio, AxesOrigin Ø 81900, 0<, Ticks Ø NoneD;

circles = 8White, [email protected], [email protected]Ò, [email protected], 1.3

Next, we show the plots as a grid. Note how only the plots with vertical lines are able to clearly reveal the missing observations:

Chapter 8 • Graphics for Data

241

[email protected], p2, p3<, 8p4, p5, p6<, 8p7, p8, p9<<, ImageSize Ø 420, Axes Ø FalseD

‡ A Quality Plot

To get a plot of good quality for all of the hare pelt data, we define a smaller aspect ratio and our own ticks: p1 = [email protected]@haredataD, [email protected]<, AspectRatio Ø 0.2, Axes Ø True, AxesOrigin Ø 81843, 0<, Ticks Ø [email protected], 1930, 10D, [email protected], 140, 20D<, ImageSize Ø 420D 140 120 100 80 60 40 20 1850

1860

1870

1880

1890

1900

1910

1920

Using a fill shows very clearly the shape of the data: [email protected], Mesh Ø All, Filling Ø Axis, AspectRatio Ø 0.2, AxesOrigin Ø 81843, 0<, Ticks Ø [email protected], 1930, 10D, [email protected], 140, 20D<, ImageSize Ø 420D

1930

242

Mathematica Navigator

Generally, a plot can be considered to consist of some line segments that go up or down. The slope of a segment indicates the orientation of the segment. For example, if the slope is 1, we say that the line segment has an orientation of 45 ±. The orientations of the segments have an effect on how well the information contained in a plot can be perceived. Typically, the judgments of a curve are optimized when the absolute values of the orientations of the line segments that make up the curve are approximately 45 ± (see Cleveland 1993, p. 89). The orientations can be adjusted by the aspect ratio of the plot. Choosing the aspect ratio to center the absolute orientations on 45 ± is banking to 45 ±. Banking to 45 ± in the previous plot would require an aspect ratio of approximately 0.05, but then the plot becomes very low. As a compromise, we have chosen the value 0.2. We go back to the default values of the options of Graphics: [email protected], groptsD;

8.1.3 Plots of Several Data Sets ‡ Basic Ways to Plot Data ListPlot[{data1, data2, … }] (Ÿ6) Points ListLinePlot[{data1, data2, … }] (Ÿ6) Joining lines ListLinePlot[{data1, data2, … }, Mesh Ø All] (Ÿ6) Joining lines and points ListPlot[{data1, data2, … }, Filling Ø True] (Ÿ6) Points and vertical lines ListLinePlot[{data1, data2, … }, Filling Ø True] (Ÿ6) Points and fills between the curves ListLinePlot[{data1, data2, … }, Filling Ø Axis] (Ÿ6) Points and fills between the curves and

x axis Joining Ø {True, False, … } (Ÿ6) Points for some data sets are joined, for others not ListPlot and ListLinePlot are also suitable for plotting several data sets. By default, the data sets are identified with different colors; otherwise, each data set is plotted in the same way. The first, second, third, and fourth data sets are plotted with colors resembling blue, purple, brown, and green, respectively. After that, the same colors are used slightly modified. (Note that in plots having joining lines and points, the points are blue for all data sets; only the color of the joining lines changes.) Here are some examples: [email protected]; data1 = T[email protected], 2 + 0.2 x - 3 [email protected]<, 8x, 0, 30
15

:

15

10

10

, 5

5

5

10

15

20

25

30

>

10

,

5

5

10

15

20

25

30

5

10

15

20

25

30

Chapter 8 • Graphics for Data

243

[email protected], data2<, Filling Ø TrueD, [email protected], data2<, Filling Ø TrueD, [email protected], data2<, Filling Ø Axis, Mesh Ø AllD<

:

,

>

,

‡ Defining Styles

Defining styles in ListPlot: PlotStyle Style of points PlotMarkers (Ÿ6) Markers to use for the data sets (enabling other markers besides points) FillingStyle (Ÿ6) Style of vertical lines Defining styles in ListLinePlot: PlotStyle Style of joining lines MeshStyle Style of points (same style for all data sets) PlotMarkers (Ÿ6) Markers to use for the data sets (enabling other markers besides points and allowing different styles for the data sets) FillingStyle (Ÿ6) Style of fills First, we consider defining styles of points and lines with PlotStyle and MeshStyle. Later, we consider the use of PlotMarkers and FillingStyle. ‡ Styles of Points and Lines

In our first example, we show how to define styles of points in ListPlot:

[email protected]@8data1, data2<, PlotStyle Ø ÒD & êü 8 Black, 8Gray, Black<, [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]< <, ImageSize Ø 400D 15

15

15

15

10

10

10

10

5

5

5

5

5

10 15 20 25 30

5

10 15 20 25 30

5

10 15 20 25 30

5

10 15 20 25 30

Similarly, we can define the style of joining lines with PlotStyle:

[email protected]@8data1, data2<, PlotStyle Ø ÒD & êü 8 Thick, 8Black, Thick<, [email protected], ThickD, [email protected], ThickD, [email protected], ThickD<<, ImageSize Ø 400D 15

15

15

15

10

10

10

10

5

5

5

5

0

5

10 15 20 25 30

0

5

10 15 20 25 30

0

5

10 15 20 25 30

0

5

10 15 20 25 30

244

Mathematica Navigator

To give styles for points in plots containing both points and joining lines, we can use MeshStyle; unfortunately, however, with this option we cannot define different styles of points for each data set. Indeed, the directives given apply for all data sets: [email protected], data2<, Mesh Ø All, MeshStyle Ø ÒD & êü 8Black, [email protected], [email protected]< 15

:

15

10

>

10

, 5

5

5

10

15

20

25

30

5

10

15

20

25

30

To get different styles of points for each data set, we need the PlotMarkers option. This option is explained next. ‡ Plot Markers

Normally, if we use ListPlot or if we use ListLinePlot with Mesh Ø All, each data set is plotted with the same symbol, point; only the color of the points differs between the data sets. This is a good way to show the data sets on the screen and when printed with a color printer. When printed with a grayscale printer, the colors may not be easily distinguished. Then we can use different symbols for the data sets with the PlotMarkers option. PlotMarkers (Ÿ6) Markers to use for the points; examples of values: None, Automatic, {Automatic, Tiny}, {Automatic, 10}, {"Ê", "Á"}, {{"Ê", 10}, {"Á", 10}}, {{gr1, 0.08}, {gr2, 0.08}}

The default value of PlotMarkers is None, meaning that all data sets are plotted with points. If we use the value Automatic, then the first five data sets are plotted with the following filled symbols: blue disk, purple square, brown diamond, green upward triangle, and blue downward triangle. If more data sets are plotted, the same symbols are used unfilled. The value of the option can also be of the form {Automatic, size}, where the size of the symbol refers to font size; for the size, we can also use the special symbols Tiny, Small, Medium, and Large. The value of the option can also be a list of symbols such as {"Ê", "Á"}. Such symbols can be picked from the SpecialCharacters palette or typed, for example, as \[FilledCircle] or \[EmptyCircle]. The size of the symbols can be told as in {{"Ê", 10}, {"Á", 10}}. In addition, a symbol can be a graphic we have created ourselves. Now the size of the symbol is a fraction of the width of the plot. First, we use the automatic symbols:

[email protected]; data1 = [email protected], 2 + 0.2 x - 3 [email protected]<, 8x, 0, 10
Chapter 8 • Graphics for Data

245

[email protected], data2<, PlotMarkers Ø ÒD & êü 8Automatic, 8Automatic, Tiny<, 8Automatic, 10<< 8 6

‡ :4 2

‡ ‡

‡ ‡ ‡ ‡ Ê

Ê

Ê

Ê Ê

2

4





8



‡ ‡

6

‡ ‡

, Ê Ê Ê 6

Ê



,

‡ Ê

Ê

Ê

Ê Ê

Ê

Ê

Ê

Ê

10

2

4

6

4‡ 2

Ê

8

Ê

‡ ‡

‡ ‡

6







2

Ê Ê 8

4



8 ‡



‡ ‡ Ê

Ê

10

Ê

Ê Ê

2





‡ ‡

>

Ê Ê Ê

4

6

Ê Ê Ê 8

10

The size of the symbol is defined with the PlotMarkers option, but the color can be defined with the PlotStyle option:

[email protected], data2<, PlotMarkers Ø Automatic, PlotStyle Ø ÒD & êü 8Black, 8Red, Blue<< 8

‡ ‡

6

‡ :4 2

‡ ‡ ‡

‡ Ê

Ê

Ê

Ê Ê

2

4



8



‡ ‡

6

‡ ‡

, Ê Ê Ê 6

Ê 8

4‡ 2

Ê Ê

‡ ‡ ‡

‡ Ê

Ê

10

Ê

Ê Ê

2

4





‡ ‡

>

Ê Ê Ê 6

Ê Ê Ê 8

10

Next, we use special symbols:

[email protected], data2<, PlotMarkers Ø ÒD & êü 88"Á", "Ê"<, 88"Ï", 8<, 8"Ê", 8<<, 8"1", "2"<< Ê

8

Ê Ê Ê

6

:4

Ê Á Á

Á 2

8

Ê

Ê Ê

Á Á

4

, Á Á Á Á 6

4Ê 2

Á Á 8

Ï

10

Ê Ê

Ê Ê

6

Ê

Ê

2

Ê

Ê Ê Ï

Ï

Ï Ï

2

4

Ê

2

,

6

Ï

2

2

2 1

1

1

1 1

1

1

2

4

6

Lastly, we define two symbols with Graphics: gr1 = [email protected], [email protected]
[email protected], data2<, PlotMarkers Ø 88gr1, 0.07<, 8gr2, 0.07<
8

6

6

:4

,

2

>

4 2

2

4

6

8

10

2

4

6

8

10

>

2

1

10

2

2

2

42 2

Ï Ï 8

2

6

Ê Ê

Ï Ï Ï

2

8

Ê

1

1 8

1 10

246

Mathematica Navigator

‡ Styles of Fills

To give styles for the vertical lines or for the fill between two data sets, use FillingStyle: [email protected], data2<, Filling Ø True, FillingStyle Ø BlackD, [email protected], data2<, Filling Ø True, FillingStyle Ø [email protected], [email protected], [email protected], data2<, Filling Ø True, FillingStyle Ø [email protected]@0.3D, BrownDD< 8

8

6

6

:4

,

2

4

,

>

2

2

4

6

8

10

2

4

6

8

10

If we want to define styles for more than one filling, the styles have to be defined within the Filling option: Filling Ø {{1 Ø {Axis, style1}, {2 Ø {{1}, style2}, … } [email protected], data2<, Filling Ø 81 Ø 8Axis, Green<, 2 Ø 881<, Blue<
:4

>

,

2

2

4

6

8

10

Next, we plot the cumulative sums of three data sets: data1 = [email protected], 2<, 820
[email protected]@8data1, data2, data3
:

4

,

>

3 2 1 5

10

15

20

‡ Example

We consider again the numbers of hare pelts sold to the Hudson Bay Trading Company in Canada from 1844 to 1934; this example was examined in Section 8.1.2, p. 240. We first use the default symbols and line styles but somewhat reduce the size of the points:

Chapter 8 • Graphics for Data

247

haredata = [email protected]"êUsersêheikkiêDocumentsêMNDataêhare", "Table"D; lynxdata = [email protected]"êUsersêheikkiêDocumentsêMNDataêlynx", "Table"D 881844, 6<, 81845, 14<, 81846, 22<, 81847, 36<, 81848, 29<, 81849, 7<, 81850, 2<, 81851, 1<, 81852, 1<, 81853, 1<, 81854, 5<, 81855, 13<, 81856, 16<, 81857, 25<, 81858, 14<, 81859, 8<, 81860, 3<, 81861, 2<, 81862, 1<, 81863, 3<, 81864, 10<, 81865, 27<, 81866, 58<, 81867, 30<, 81868, 26<, 81869, 9<, 81870, 4<, 81871, 2<, 81872, 2<, 81873, 6<, 81874, 10<, 81875, 26<, 81876, 29<, 81877, 21<, 81878, 11<, 81879, 10<, 81880, 5<, 81881, 3<, 81882, 5<, 81883, 16<, 81884, 42<, 81885, 64<, 81886, 63<, 81887, 32<, 81888, 15<, 81889, 7<, 81890, 3<, 81891, 4<, 81897, 15<, 81898, 7<, 81899, 2<, 81900, 3<, 81901, 5<, 81902, 14<, 81903, 27<, 81904, 47<, 81905, 54<, 81906, 29<, 81907, 7<, 81908, 2<, 81909, 2<, 81910, 4<, 81911, 10<, 81912, 14<, 81913, 19<, 81915, 8<, 81916, 9<, 81917, 2<, 81918, 1<, 81919, 1<, 81920, 2<, 81921, 4<, 81922, 4<, 81923, 8<, 81924, 7<, 81925, 9<, 81926, 7<, 81927, 4<, 81928, 3<, 81929, 2<, 81930, 3<, 81931, 3<, 81932, 5<, 81933, 7<, 81934, 7<<

opts = [email protected] Ø 0.2, AxesOrigin Ø 81843, 0<, Ticks Ø [email protected], 1930, 10D, [email protected], 140, 20D<, ImageSize Ø 420
1860

1870

1880

1890

1900

1910

1920

1930

Both hare and lynx seem to have a cycle of approximately 10 years. More than 90% of the diet of the lynx is hare. When there are few hares available, lynx starve rather than eat other species. The two data sets are not very clearly distinguished in the previous plot because the color and the symbol of the points are the same for both data sets (the color of the lines is different, however). Next, we use our own symbols: gr1 = [email protected], [email protected]
1860

1870

1880

1890

1900

1910

1920

1930

Now the two data sets can be seen more clearly (note that we have made the size of the black disks slightly larger than the size of the circles so that both seem to be approximately the same size). A filled plot also gives a good illustration:

248

Mathematica Navigator

[email protected], lynxdata<, Mesh Ø All, opts, PlotStyle Ø Black, Filling Ø Axis, PlotMarkers Ø 88gr1, 0.038<, 8gr2, 0.036<
‡ Self-Made Plotting

Plotting several data sets with Graphics, using the primitives Line, Point, and Disk with suitable directives, is very straightforward: [email protected]@haredataD, [email protected], [email protected], [email protected], White, [email protected], [email protected]Ò, [email protected], 1

hare

lynx 1850

1860

1870

1880

1890

1900

1910

1920

1930

‡ A Phase Plot

Until now, we have plotted two data sets~Hx1 , x2 , …L and Iy1 , y2 , …M~as time series. Another kind of

plot is obtained by plotting the pairs Ixi , yi M. In this way, we get a plot that is analogous to a phase plot of the solution of a pair of differential equations (see Section 26.3.2, p. 855). For the years 1909 to 1934, the numbers of hare and lynx pelts are as follows (the observation for the year 1914 is lacking):

harelynx = 8825, 2<, 850, 4<, 855, 10<, 875, 14<, 870, 19<, 830, 8<, 820, 9<, 815, 2<, 815, 1<, 820, 1<, 835, 2<, 860, 4<, 880, 4<, 885, 8<, 860, 7<, 830, 9<, 820, 7<, 810, 4<, 85, 3<, 85, 2<, 810, 3<, 830, 3<, 880, 5<, 8100, 7<, 880, 7<<;

We construct a phase plot: [email protected], Mesh Ø All, Epilog Ø [email protected], [email protected], [email protected]@harelynxDD<, AxesLabel Ø 8"hare", "lynx"<, ImageSize Ø 200D lynx

15

10

5

20

40

60

80

100

hare

Chapter 8 • Graphics for Data

249

The starting point H25, 2L is red and larger than the other points. We can see a counterclockwise cycle; this pattern is typical for a predator-prey system.

8.2 Scatter Plots 8.2.1 Scatter Plots Thus far, we have presented plotting methods for showing each dependent variable separately, typically as time series. Now we present some plotting methods that show two or even more dependent variables in the same plot. Such plots are useful when studying relationships among a number of dependent variables. We study scatter plots and quantile-quantile plots. In a scatter plot, we plot one variable against another variable. Such a plot may yield valuable information about the connections between the variables. A pairwise scatter plot, which is also called a scatter plot matrix or a correlation plot, is a collection of plots in which each plot shows one variable against another variable. A scatter plot matrix is among the best ways to illustrate multidimensional data. ‡ Example 1

As an example, we consider the data file environmental , which contains 111 observations of ozone, radiation, temperature, and wind in New York City from May to September of 1973. The data are from a collection of data sets in http://lib.stat.cmu.edu/S/visualizing.data . All of the data are visualized in Cleveland (1993), and the data sets are also on the CD-ROM that comes with this book (the data sets are reproduced with the permission of the publisher, Hobart Press). We also consider the environmental data set in Section 30.5.3, p. 1038, when presenting local regression. On my computer, the environmental data are in a text file environmental in a folder visdata . First, we read the data (Rest drops the first row containing the headings of the columns; for reading data, see Section 4.2.1, p. 100): [email protected] = [email protected] [email protected]"êUsersêheikkiêDocumentsêMNDataêvisdataêenvironmental", "Table"DD, 6D

881, 41, 190, 67, 7.4<, 82, 36, 118, 72, 8.<, 83, 12, 149, 74, 12.6<, 84, 18, 313, 62, 11.5<, 85, 23, 299, 65, 8.6<, 86, 19, 99, 59, 13.8<, 87, 8, 19, 61, 20.1<, 88, 16, 256, 69, 9.7<, 89, 11, 290, 66, 9.2<, 810, 14, 274, 68, 10.9<, 811, 18, 65, 58, 13.2<, 812, 14, 334, 64, 11.5<, 813, 34, 307, 66, 12.<, 814, 6, 78, 57, 18.4<, 815, 30, 322, 68, 11.5<, 816, 11, 44, 62, 9.7<, 817, 1, 8, 59, 9.7<, 818, 11, 320, 73, 16.6<, 819, 4, 25, 61, 9.7<, 820, 32, 92, 61, 12.<, 821, 23, 13, 67, 12.<, 822, 45, 252, 81, 14.9<, 823, 115, 223, 79, 5.7<, 824, 37, 279, 76, 7.4<, 825, 29, 127, 82, 9.7<, 826, 71, 291, 90, 13.8<, 827, 39, 323, 87, 11.5<, 828, 23, 148, 82, 8.<, 829, 21, 191, 77, 14.9<, 830, 37, 284, 72, 20.7<, 831, 20, 37, 65, 9.2<, 832, 12, 120, 73, 11.5<, 833, 13, 137, 76, 10.3<, 834, 135, 269, 84, 4.<, 835, 49, 248, 85, 9.2<, 836, 32, 236, 81, 9.2<, 837, 64, 175, 83, 4.6<, 838, 40, 314, 83, 10.9<, 839, 77, 276, 88, 5.1<, 840, 97, 267, 92, 6.3<, 841, 97, 272, 92, 5.7<, 842, 85, 175, 89, 7.4<, 843, 10, 264, 73, 14.3<, 844, 27, 175, 81, 14.9<, 845, 7, 48, 80, 14.3<, 846, 48, 260, 81, 6.9<, 847, 35, 274, 82, 10.3<, 848, 61, 285, 84, 6.3<, 849, 79, 187, 87, 5.1<, 850, 63, 220, 85, 11.5<, 851, 16, 7, 74, 6.9<, 852, 80, 294, 86, 8.6<, 853, 108, 223, 85, 8.<, 854, 20, 81, 82, 8.6<, 855, 52, 82, 86, 12.<, 856, 82, 213, 88, 7.4<, 857, 50, 275, 86, 7.4<, 858, 64, 253, 83, 7.4<, 859, 59, 254, 81, 9.2<, 860, 39, 83, 81, 6.9<, 861, 9, 24, 81, 13.8<, 862, 16, 77, 82, 7.4<, 863, 122, 255, 89, 4.<, 864, 89, 229, 90, 10.3<, 865, 110, 207, 90, 8.<, 866, 44, 192, 86, 11.5<, 867, 28, 273, 82, 11.5<, 868, 65, 157, 80, 9.7<, 869, 22, 71, 77, 10.3<, 870, 59, 51, 79, 6.3<, 871, 23, 115, 76, 7.4<, 872, 31, 244, 78, 10.9<, 873, 44, 190, 78, 10.3<, 874, 21, 259, 77, 15.5<, 875, 9, 36, 72, 14.3<, 876, 45, 212, 79, 9.7<, 877, 168, 238, 81, 3.4<, 878, 73, 215, 86, 8.<, 879, 76, 203, 97, 9.7<, 880, 118, 225, 94, 2.3<, 881, 84, 237, 96, 6.3<, 882, 85, 188, 94, 6.3<, 883, 96, 167, 91, 6.9<, 884, 78, 197, 92, 5.1<, 885, 73, 183, 93, 2.8<, 886, 91, 189, 93, 4.6<, 887, 47, 95, 87, 7.4<, 888, 32, 92, 84, 15.5<, 889, 20, 252, 80, 10.9<, 890, 23, 220, 78, 10.3<, 891, 21, 230, 75, 10.9<, 892, 24, 259, 73, 9.7<, 893, 44, 236, 81, 14.9<, 894, 21, 259, 76, 15.5<, 895, 28, 238, 77, 6.3<, 896, 9, 24, 71, 10.9<, 897, 13, 112, 71, 11.5<, 898, 46, 237, 78, 6.9<, 899, 18, 224, 67, 13.8<, 8100, 13, 27, 76, 10.3<, 8101, 24, 238, 68, 10.3<, 8102, 16, 201, 82, 8.<, 8103, 13, 238, 64, 12.6<, 8104, 23, 14, 71, 9.2<, 8105, 36, 139, 81, 10.3<, 8106, 7, 49, 69, 10.3<, 8107, 14, 20, 63, 16.6<, 8108, 30, 193, 70, 6.9<, 8109, 14, 191, 75, 14.3<, 8110, 18, 131, 76, 8.<, 8111, 20, 223, 68, 11.5<<

Extract the columns of the data:

8no, ozone, radiation, temperature, wind< = data¨;

We are interested in how ozone depends on the other variables. Thus, we plot ozone against radiation, temperature, and wind:

250

Mathematica Navigator

GraphicsRowA9ListPlotA8radiation, ozone<¨, PlotStyle Ø [email protected]lD, Frame Ø True, FrameLabel Ø 8"radiation", "ozone"
ListPlotA8temperature, ozone<¨, PlotStyle Ø [email protected], Frame Ø True, FrameLabel Ø 8"temperature", None
ListPlotA8wind, ozone<¨, PlotStyle Ø [email protected], Frame Ø True,

ozone

FrameLabel Ø 8"wind", None<, Axes Ø FalseE=, ImageSize Ø 420, Spacings Ø -40E

150

150

150

100

100

100

50

50

50

0

0 0

50

100 150 200 250 300

60

radiation

70

80

90

0 0

temperature

5

10

15

20

wind

We can see that ozone values are high when radiation or temperature is high (a positive correlation) or wind is low (a negative correlation); however, a high value of radiation does not necessarily mean a high ozone value. ‡ Example 2

With CountryData (see Section 9.2.1, p. 293), we can study many properties of countries. Here, we investigate life expectancy against birth rate fraction and literacy fraction: co = [email protected]"Countries"D; birth = [email protected]@Ò, "BirthRateFraction"D, [email protected]Ò, "LifeExpectancy"D<, ÒD & êü co; literacy = [email protected]@Ò, "LiteracyFraction"D, [email protected]Ò, "LifeExpectancy"D<, ÒD & êü co;

The corresponding scatter plots are as follows:

[email protected]@birth, Frame Ø True, AxesOrigin Ø 80, 30<, FrameLabel Ø 8"Birth rate fraction", "Life expectancy"
The life expectancy is higher the lower the birth rate or the higher the literacy fraction. By using Tooltip, the plots have the property that the names of the countries can be seen by moving the mouse

(without pressing a button) over the points.

Chapter 8 • Graphics for Data

251

‡ Example 3

In Example 2, we used Tootip to show the countries corresponding to the points. Such labels cannot be seen in a printed document. Here, we show how we can easily produce a plot with explicit labels. As an example, we plot the body and brain weights of some animals. The data are from the same visdata collection as we considered in Example 1; the collection also comes on the CD-ROM of this book.

On my computer, the animal data are in a text file modAnimal in a folder visdata . (Note that the original file animal contained spaces in the names of the animals, but we have now deleted the spaces.) We read the file and take only rows 38 through 48: data = [email protected]"êUsersêheikkiêDocumentsêMNDataêvisdataêmodAnimal", "Table"D; 8no, name, body, brain< = [email protected], 838, 48
We use Graphics to get a plot with labels for the points. As can be seen, overlapping labels may be a problem with labeled plots: GraphicsA9PointA8body, brain<¨E,

[email protected]Ò1, Ò2, 8-1.3, 0
Brain weight

GraySeal 300

200 Sheep

GrayWolf Goat RoeDeer GiantArmadillo Kangaroo

100

0

Pig BrazilianTapir

Jaguar

0

50 000

100 000

150 000

200 000

Body weight

‡ Scatter Plot Matrix

In the StatisticalPlots` package: PairwiseScatterPlot[data] Plot multidimensional data as a pairwise scatter plot

Options: DataLabels Labels for the variables; examples of values: None, {"X", "Y", "Z"} DataTicks Ticks for the variables; examples of values: None, Automatic DataSpacing Space between the subgraphs; examples of values: 0, 0.05 DataRanges Ranges for the data; default value: All PlotDirection Direction in which scatter plots are generated; examples of values: {Right, Down}, {Right, Up} PlotStyle Style of the points; examples of values: Automatic, PointSize[Small]

252

Mathematica Navigator

As an example, we consider the data of Example 1: << StatisticalPlots` 8radiation, temperature, wind, ozone<¨, PlotStyle Ø [email protected], DataLabels Ø 8"radiation", "temperature", "wind", "ozone"<, PlotDirection Ø 8Right, Up<, ImageSize Ø 330E

PairwiseScatterPlotA

ozone

wind

temperature

radiation

radiation

temperature

wind

ozone

Of these 16 plots, we plotted, in Example 1, the first three in the top row. For more about the statistical plots package, look at StatisticalPlotsêguideêStatisticalPlotsPackage.

8.2.2 Quantile-Quantile Plots In the StatisticalPlots` package: QuantilePlot[data1, data2] Create a quantile-quantile plot

Options: PlotMarkers Markers for the points; examples of values: Automatic, {Automatic, 3}, None ReferenceLineStyle Style of the reference line; examples of values: Automatic, None Joined Whether the points are joined with lines; possible values: False, True PlotStyle Style of the joining line; default value: Automatic

A quantile-quantile plot or a q-q plot (see Cleveland 1993, p. 21) is a powerful method for comparing the distributions of two or more sets of univariate data. The plot is a special scatter plot: It shows the quantiles of one data set against the quantiles of another data set. If the resulting points are close to a line with a slope of 1, this supports the hypothesis that the distributions of the two data sets are the same.

Chapter 8 • Graphics for Data

253

QuantilePlot first determines the interpolated quantiles of the shorter of the two data sets at the equivalent positions in the longer data set. It then plots the two sets of quantiles against each other.

As an example, generate data sets from a Student t-distribution with parameter 10 and from the standard normal distribution: [email protected]; ran1 = [email protected]@10D, 82000
How close are the two distributions? Prepare a q-q plot:

[email protected], ran2, PlotMarkers Ø 8Automatic, 2<, ImageSize Ø 200D Ê Ê

3

Ê

ÊÊ Ê Ê ÊÊ Ê ÊÊ ÊÊ Ê Ê Ê Ê ÊÊ Ê ÊÊ ÊÊ ÊÊÊÊ Ê Ê ÊÊÊ Ê Ê Ê Ê Ê Ê ÊÊÊ Ê Ê Ê Ê ÊÊÊ Ê Ê Ê ÊÊ Ê Ê Ê Ê Ê ÊÊ Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê ÊÊ Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê ÊÊ Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê Ê ÊÊ Ê ÊÊ Ê Ê Ê Ê Ê ÊÊ ÊÊ ÊÊ ÊÊÊ Ê ÊÊ Ê Ê ÊÊ Ê Ê ÊÊÊ ÊÊ Ê Ê ÊÊÊ Ê Ê ÊÊÊ ÊÊÊ ÊÊ ÊÊ Ê ÊÊ Ê Ê

ÊÊ Ê ÊÊ

2 1

-4

-2

2

4

-1 -2

Ê Ê Ê

Ê

Ê Ê Ê ÊÊ

Ê

-3

We see that the points are not sufficiently close to the reference line for supporting the hypothesis that the distributions are the same. Indeed, although we know that the t-distribution approaches the normal distribution as the parameter approaches infinity, the value 10 simply is not large enough. The tails of the t-distribution are fatter than the tails of the normal distribution.

8.3 Bar Charts 8.3.1 Bar Charts ‡ Bar Charts

The BarCharts` package contains several commands for bar charts. BarChart, StackedBarChart, and PercentileBarChart are suitable for charts in which the bars are simply drawn side by side (without having specified positions) and in which there are labels (not coordinates) under the bars. GeneralizedBarChart is designed for charts in which the bars have specified positions and widths. Histogram (see Section 8.3.2, p. 258) is a special command to calculate frequencies and plot them as bar

charts. We also have BarChart3D, GeneralizedBarChart3D, and Histogram3D (see Section 8.6.1, p. 275). In the BarCharts` package: BarChart[{y1 , y2 , … }] Plot bars of heights y1 , y2 , … and label the bars by 1, 2, … data = 84, 7, 6, 3, 5, 4, 8, 7<; << BarCharts`

254

Mathematica Navigator

[email protected]

‡ Options BarChart accepts the following options and the options used with Graphics. For BarChart, the default

value of AspectRatio is 1/GoldenRatio and that of Axes is True. Options of BarChart: BarLabels Labels under the bars; examples of values: Automatic, {"A", "B", "C"} BarValues Whether to write the values on top of the bars; possible values: False, True BarOrientation Orientation of the bars; possible values: Vertical, Horizontal BarGroupSpacing The space between each group of bars as a fraction of the width of one bar;

examples of values: Automatic (means 0.2), 0 BarSpacing The space between the bars within a group as a fraction of the width of one bar;

examples of values: Automatic (means 0), 0.1, -0.4 BarStyle Style inside the edges of the bars; examples of values for one data set: Automatic (means Hue[0.67, 0.45, 0.65]), Gray; an example for two data sets: {Gray, GrayLevel[0.9]} BarEdgeStyle Style of the edges of the bars; examples of values for one data set: Opacity[0.5], Black, Directive[Gray, Thickness[Medium]]; an example for two data sets: {Thickness[Medium], Directive[Gray, Thickness[Medium]]} BarEdges Whether edges are drawn for the bars; possible values: True, False BarGroupSpacing defines the space between each group of bars. Indeed, BarChart can generate bars for multiple data sets, and then the bars are collected into groups; each group contains as many bars as there are data sets. Thus, if we only have one data set, then BarGroupSpacing simply defines the space between the bars. The default value Automatic means the value 0.2. If you want no space between the bars, give the value0. BarSpacing defines the space between bars within a group of bars. The default value Automatic means the value 0: There is no space between the bars within a group. If you want a small space between the bars, give a small positive value for the option, and if you want the bars to overlap, give a small negative value. [email protected], BarLabels Ø [email protected]"a", "h"DD, [email protected], BarValues Ø TrueD, [email protected], BarOrientation Ø HorizontalD<

:

,

,

>

Chapter 8 • Graphics for Data

255

[email protected], BarGroupSpacing Ø 0D, [email protected], BarStyle Ø [email protected], 0.4DD, BarChartAdata, Ticks Ø [email protected]D, [email protected]"a", "h"D<¨, [email protected]=E=

:

,

,

>

The last example is about defining ticks (the symbol  means a transpose; type it as ÂtrÂ). Suppose we want to make a bar chart like the first plot shown previously, except that we want to define new y ticks. A problem is that giving a value to Ticks causes BarLabels to no longer be taken into account. Thus, if we use Ticks, we also have to redefine the labels with the aid of Ticks; this is done in the last example. ‡ Example 1

As an example, we plot the body and brain weights of some animals. This data set was also considered in Example 3 of Section 8.2.1, p. 251. We read the file and take only rows 38 through 48: data0 = [email protected]"êUsersêheikkiêDocumentsêMNDataêvisdataêmodAnimal", "Table"D; 8no, name, body, brain< = [email protected], 838, 48
Next, we form pairs of brain weight and animal name and sort the pairs in ascending order according to brain weight: data = SortA8brain, name<¨E 8856., Kangaroo<, 881., GiantArmadillo<, 898.2, RoeDeer<, 8115., Goat<, 8119.5, GrayWolf<, 8157., Jaguar<, 8169., BrazilianTapir<, 8175., Sheep<, 8180., Pig<, 8325., GraySeal<, 8419., Donkey<<

The bar chart is given as follows: p1 = [email protected], AspectRatio Ø 0.25, ImageSize Ø 420D

Here, we have used a large image size to avoid the overlapping of the labels. In the next example, we present other solutions to this problem.

256

Mathematica Navigator

‡ Example 2

A solution to overlapping labels is to use horizontal bars: [email protected], BarOrientation Ø Horizontal, ImageSize Ø 250D

Text primitives can have any slope. We define the slope as {4, 3}; that is, the slope is 3 ê 4. We also

Another solution is to give a suitable slope to the labels. Remember from Section 6.2.6, p. 163, that

adjust the positioning of the labels: The old position in text coordinates is {0, 1} so that the labels are centered below the bars, but the new position is {0.8, 0.8} so that the labels are to the left of the bars: [email protected]@p1D ê. [email protected]_String, b_, c_D Ø [email protected], b, 80.8, 0.8<, 84, 3
‡ Several Data Sets

In the BarCharts` package: BarChart[{data1, data2, … }] StackedBarChart[{data1, data2, … }] PercentileBarChart[{data1, data2, … }] BarChart can also be used for multiple data sets. As an example, we plot the running times of four algorithms before and after improvements (these are not real data; we illustrate the same data sets with

a dot plot in Section 8.4.1, p. 260). The default is that the bars are side by side, but we produce a plot in which the bars somewhat overlap:

Chapter 8 • Graphics for Data

257

p = BarChartA888, 9, 11, 10<, 85, 7, 6, 8<<, BarLabels Ø 8"Alg. 1", "Alg. 2", "Alg. 3", "Alg. 4"<, BarGroupSpacing Ø 0.6, BarSpacing Ø -0.4, BarStyle Ø [email protected], [email protected]<, PlotLabel Ø StyleA"Running times before HdarkL and\nafter HlightL improvements", 8E, ImageSize Ø 200E

‡ Bars with Positions

In the BarCharts` package: GeneralizedBarChart[{{x1 , y1 , w1 }, {x2 , y2 , w2 }, … }] Plot bars of heights y1 , y2 , … and widths w1 , w2 , … at the positions x1 , x2 , …

Recall that BarChart produces bars side by side, with possible labels. With GeneralizedBarChart we can define the positions of the bars. GeneralizedBarChart has the same options as BarChart except for the options BarLabels, BarGroupSpacing, and BarSpacing. The options are in fact unnecessary because the labels can be given

with the Ticks option, and the spacing can be adjusted with the widths of the bars. In this example, we toss a die 100 times and calculate and plot the frequencies. Note that for each frequency, we add the width 1 of the bar as the third component: [email protected]; data = [email protected], 6<, 100D;

freq = 8Ò, [email protected], ÒD, 1< & êü [email protected]

881, 17, 1<, 82, 14, 1<, 83, 22, 1<, 84, 16, 1<, 85, 14, 1<, 86, 17, 1<< [email protected], AxesOrigin Ø 80.5, 0<, ImageSize Ø 120D

In this example, Histogram would be the correct command, but we used GeneralizedBarChart just to illustrate this command. Histogram is considered in the next section.

258

Mathematica Navigator

8.3.2 Histograms With Histogram we can plot frequencies as a bar chart; the data can be either raw data or frequencies. In the former case, Histogram first calculates the frequencies. In the Histograms` package: Histogram[{x1 , x2 , … }] Plot the frequencies of the given raw data Histogram[{f1 , …, fn }, FrequencyData Ø True, HistogramCategories Ø cats] Plot the given

frequencies Options: HistogramCategories How the data is categorized~that is, for which intervals the frequencies are

calculated; possible values: Automatic (use an internal algorithm), a positive integer n (use exactly n categories of equal width, if ApproximateIntervals Ø False, and about n categories, if ApproximateIntervals Ø True), or a list of cutoff values {c0 , c1 , …, cn } (calculate the frequencies in the intervals [c0 , c1 ), …, [cn-1 , cn )) ApproximateIntervals Whether interval boundaries should be approximated by simple numbers;

possible values: Automatic (usually means True), True, False HistogramScale Whether to scale the heights of the bars; examples of values: Automatic (means False for categories with equal widths and True for categories with unequal widths), False (no scaling: plot frequencies as such), True (scale by dividing the heights by the widths of the bars to get a frequency density), 1 (scale to get the sum of the areas of the bars equal to 1 so that the histogram approximates the probability density function of the data; other constants can also be used) HistogramRange Range of data to be included in the histogram; examples of values: Automatic (means that all data are included), {0, 10} BarOrientation, BarStyle, BarEdgeStyle, BarEdges (see Section 8.3.1, p. 254) Histogram also has the options of Graphics. For Histogram, the default value of AspectRatio is 1/GoldenRatio and that of Axes is True.

We plot the frequencies of the same data that were used in Section 8.3.1, p. 257. In the first plot that follows, we used raw data. In the second plot, we used the frequencies we had calculated ourselves. << Histograms` [email protected]; data = [email protected], 6<, 100D; freq = [email protected], ÒD & êü [email protected] 817, 14, 22, 16, 14, 17<

[email protected], HistogramCategories Ø [email protected], 6.5, 1DD, [email protected], HistogramCategories Ø [email protected], 6.5, 1D, FrequencyData Ø TrueD< 20

20 15

15

:10

,

>

10 5

5

0 1

2

3

4

5

6

1

2

3

4

5

6

Chapter 8 • Graphics for Data

259

With ParetoPlot from the StatisticalPlots` package, we can plot bars for the frequencies together with a line plot for the cumulative frequencies. In Section 30.2, p. 1011, we consider the calculation of frequencies and the plotting of histograms in more detail.

8.3.3 Stem-and-Leaf Plots In the StatisticalPlots` package: StemLeafPlot[vector] Create a stem-and-leaf plot for one data set StemLeafPlot[vector1, vector2] Create a stem-and-leaf plot for two data sets

Options: Leaves How leaves are represented; examples of values: "Digits", "Tallies", {"Tallies", "TallySymbol" Ø Ê, "LeafWrapping" Ø 20}, None IncludeStemCounts Whether to include column(s) for counts; possible values: False, True IncludeEmptyStems Whether stems within the data range without leaves should be included;

possible values: False, True ColumnLabels Labels for the columns; examples of values: Automatic, {"Values", "Tallies"} x

StemExponent If the value is x, the stem unit is 10 ; examples of values: Automatic (the exponent is

chosen based on the magnitudes of the data), 2 IncludeStemUnits Whether a reminder of the stem units should be included; possible values: True, False

The StemExponent and Leaves options have a number of suboptions (some of them are shown above); see StatisticalPlots/tutorial/StatisticalPlots in the Documentation Center. Options of GridBox (e.g., RowLines Ø True) can also be used. A stem-and-leaf plot is like a histogram: It shows how many observations fall into some categories. An example: data = 83.26, 1.4, 4.33, 3.6, 1.27, 3.5<; << StatisticalPlots` << Histograms`

[email protected], IncludeEmptyStems Ø TrueD, [email protected], ImageSize Ø 130D< Stem 1 2 : 3 4

Leaves 34 356 3

Stem units: 1

3.0 2.5 2.0 , 1.5 1.0 0.5

>

2

3

4

5

The first “plot” shows that two values have integer part 1; their first (rounded) decimals are 3 and 4. We have no values that have integer part 2. Three values have integer part 3; their first decimals are 3, 5, and 6. Lastly, one value has integer part 4; its first decimal is 3. One advantage of a stem-and-leaf plot over a histogram is that we can also read the approximate values of the individual observations. In addition, we can easily compare two data sets. In the following, we compare a binomial distribution with the corresponding approximate Poisson distribution: [email protected]; data1 = [email protected]@50, 0.05D, 50D; data2 = [email protected]@50 μ 0.05D, 50D;

260

Mathematica Navigator

[email protected], data2, Leaves Ø 8"Tallies", "TallySymbol" Ø Ê<, ColumnLabels Ø 8"Counts", "Tallies", "Values", "Tallies", "Counts"<, IncludeStemCounts Ø True, IncludeStemUnits Ø FalseD Counts 4 8 14 12 7 3 1 1

Tallies ÊÊÊÊ ÊÊÊÊÊÊÊÊ ÊÊÊÊÊÊÊÊÊÊÊÊÊÊ ÊÊÊÊÊÊÊÊÊÊÊÊ ÊÊÊÊÊÊÊ ÊÊÊ Ê Ê

Values 0 1 2 3 4 5 6 7

Tallies ÊÊ ÊÊÊÊÊÊÊÊÊÊÊ ÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊ ÊÊÊÊÊÊÊÊÊÊ ÊÊÊÊÊÊÊÊÊ Ê Ê

Counts 2 11 16 10 9 0 1 1

8.4 Other Plots 8.4.1 Dot Plots A dot plot can be drawn with the following program: [email protected]_, labels_, styles_, 8xmin_, xmax_<, xticks_, grid_, opts___D := ModuleA8n = [email protected], vlines, hlines, points<, vlines = [email protected] ã 8<, 8<, 8Gray, [email protected]@88i, 0.3<, 8i, n + 0.7<<, 8i, gridP1T, gridP2T, gridP3T
Here, values is a list of one or more data sets, with each data set being a list of numbers; labels is a list containing the labels for the y axis. The variable styles is a list of styles for the points: The list has as many components as there are data sets, with each component being a list of two elements giving the point size and color of the points; styles can also be an empty list {}, and then default styles are used. The variables xmin and xmin define the x range; xticks defines the ticks on the x axis; and grid defines a list of three numbers giving the position of the first vertical grid line, position of the last vertical line, and the increment of the grid lines (an empty list {} can also be given). In addition, we can give options of Graphics. ‡ Example 1

To illustrate dot plots, we use the same animal brain weight data we considered, with horizontal bar charts, in Section 8.3.1, p. 256: data = [email protected]"êUsersêheikkiêDocumentsêMNDataêvisdataêmodAnimal", "Table"D; 8no, name, body, brain< = [email protected], 838, 48
Sort according to the brain weights:

Chapter 8 • Graphics for Data

261

8values, labels< = SortA8brain, name<¨E¨ 8856., 81., 98.2, 115., 119.5, 157., 169., 175., 180., 325., 419.<, 8Kangaroo, GiantArmadillo, RoeDeer, Goat, GrayWolf, Jaguar, BrazilianTapir, Sheep, Pig, GraySeal, Donkey<<

Prepare a dot plot:

[email protected]<, labels, 8<, 80, 460<, Automatic, 8100, 400, 100<, PlotLabel Ø [email protected]"Brain weights for some animals", 10, BoldD, AspectRatio Ø 1 ê GoldenRatio, ImageSize Ø 300D

Brain weights for some animals Donkey GraySeal Pig Sheep BrazilianTapir Jaguar GrayWolf Goat RoeDeer GiantArmadillo Kangaroo 0

100

200

300

400

‡ Example 2

With a dot plot we can also compare two or more data sets (another way is to use a bar chart; see Section 8.3.1, p. 256). As an example, we plot the running times of four algorithms before and after improvements (these are not real data):

labels = 8"Algorithm 1", "Algorithm 2", "Algorithm 3", "Algorithm 4"<; times1 = 88, 9, 11, 10<; times2 = 85, 7, 6, 8<; style1 = [email protected], Black<; style2 = [email protected], Gray<;

dotPlotA8times1, times2<, labels, 8style1, style2<, 80, 12<, [email protected], 8<, AspectRatio Ø 1 ê GoldenRatio, PlotLabel Ø StyleA"Running times before HblackL and\nafter HgrayL improvements", 9, BoldE, ImageSize Ø 200E Running times before HblackL and after HgrayL improvements

Algorithm 4 Algorithm 3 Algorithm 2 Algorithm 1 1

2

3

4

5

6

7

8

9

10 11

262

Mathematica Navigator

‡ Multiway Dot Plots

An effective way to illustrate 3D data is by using a multiway dot plot (Cleveland, 1993). As an example, we consider the data in the file modBarley . This file is from Cleveland (1993) and can be found on the CD-ROM accompanying this book. The file contains barley yields at six sites for 10 varieties in 1931. On my computer, the file is in a folder visdata in the folder MNata: Hdata = [email protected]"êUsersêheikkiêDocumentsêMNDataêvisdataêmodBarley", "Table"DL êê TableForm 47.3 40.5 35. 35.1 25.7 29.7 48.9 39.9 34.4 27. 29. 33. 46.8 44.1 44.2 24.7 33.1 19.7 55.2 38.1 35.1 43.1 29.7 29.1 50.2 41.3 38.8 39.9 26.3 23. 48.6 41.6 43.2 32.8 32. 34.7 63.8 46.9 46.6 36.6 33.9 29.8 65.8 48.6 47. 36.6 28.1 24.9 58.1 45.7 43.5 43.3 33.6 32.2 58.8 49.9 47.2 39.3 31.6 34.5

This file is a slightly modified version of the original file barley. In modBarley , we have somewhat rearranged the rows and columns of barley. The sites and varieties of the barley are as follows: sites = 8"Waseca", "Crookston", "Morris", "Univ. Farm", "Duluth", "Gr. Rapids"<; varieties = 8"Svansota", "Manchuria", "No. 475", "Glabron", "Velvet", "Peatland", "Trebi", "No. 462", "No. 457", "Wisconsin"<;

Calculate the total mean of all 60 yields: tmean = [email protected]@dataDD 39.1183

We produce two multiway dot plots with the program dotPlot presented previously. First, we make a multiway dot plot showing the yields of the 10 varieties at each of the six sites: p1 = GraphicsColumnA [email protected]ÒP1T<, varieties, [email protected], Black<<, 80, 72<, Automatic, 8tmean, tmean, tmean<, BaseStyle Ø 85, FontFamily -> "Helvetica"<, AspectRatio Ø 0.6, ImagePadding Ø 15, PlotLabel Ø [email protected]ÒP2T, 7DD & êü I9data¨, sites=¨M, Spacings Ø 0E;

Then we make a multiway dot plot showing the yields at the six sites of each of the 10 varieties: p2 = GraphicsColumnA [email protected]ÒP1T<, [email protected], [email protected], Black<<, 80, 72<, Automatic, 8tmean, tmean, tmean<, BaseStyle Ø 85, FontFamily -> "Helvetica"<, AspectRatio Ø 0.4, ImagePadding Ø 15, PlotLabel Ø [email protected]ÒP2T, FontSize Ø 7DD & êü [email protected], dataD, varieties<¨E, Spacings Ø 0E;

Now we show both multiway dot plots side by side: [email protected], p2<, AspectRatio Ø 3.5, ImageSize Ø 400, Spacings Ø -20, PlotRangePadding Ø 0D

Chapter 8 • Graphics for Data

263

Waseca

Wisconsin aseca okston Morris Farm Duluth Rapids

consin o. 457 o. 462 Trebi atland Velvet abron o. 475 churia nsota

0

10

20

30

40

50

60

70

50

60

70

50

60

70

50

60

70

50

60

70

50

60

70

50

60

70

50

60

70

60

70

60

70

No. 457

0

10

20

30

40

50

60

70

aseca okston Morris Farm Duluth Rapids

Crookston

0

consin o. 457 o. 462 Trebi atland Velvet abron o. 475 churia nsota

10

20

30

40

No. 462 aseca okston Morris Farm Duluth Rapids 0

0

10

20

30

40

50

60

10

20

30

40

Trebi

70 aseca okston Morris Farm Duluth Rapids

Morris consin o. 457 o. 462 Trebi atland Velvet abron o. 475 churia nsota

0

10

20

30

40

Peatland aseca okston Morris Farm Duluth Rapids 0

10

20

30

40

50

60

70

0

10

20

Univ. Farm

30

40

Velvet aseca okston Morris Farm Duluth Rapids

consin o. 457 o. 462 Trebi atland Velvet abron o. 475 churia nsota

0

10

20

30

40

Glabron

0

10

20

30

40

50

60

70

aseca okston Morris Farm Duluth Rapids

Duluth

0

consin o. 457 o. 462 Trebi atland Velvet abron o. 475 churia nsota

10

20

30

40

No. 475 aseca okston Morris Farm Duluth Rapids 0

0

10

20

30

40

50

60

10

20

30

40

Manchuria

70 aseca okston Morris Farm Duluth Rapids

Gr. Rapids consin o. 457 o. 462 Trebi atland Velvet abron o. 475 churia nsota

0

10

20

30

40

50

Svansota aseca okston Morris Farm Duluth Rapids 0

10

20

30

40

50

60

70

0

10

20

30

40

50

264

Mathematica Navigator

The multiway dot plot of the first column can be used to infer how the yields of the varieties vary within each site and how the yields vary among sites in general. The multiway dot plot of the second column can be used to infer how the yield of each variety varies among the sites. The gray line in both plots is the total mean. If we want to perform detailed comparisons with the data, a multiway dot plot is among the best ways to show the data. The barley data are also considered in the next section and in Section 8.6.1, p. 280.

8.4.2 Box-and-Whisker Plots In the StatisticalPlots` package: BoxWhiskerPlot[vector] Plot vector BoxWhiskerPlot[matrix] Plot the columns of matrix BoxWhiskerPlot[vector1, vector2, … ] Plot each vector BoxQuantile If set to a (0 < a < 0.5), a box shows data from H0.5 - aL-quantile to H0.5 + aL-quantile;

Options:

examples of values: 0.25, 0.4 BoxLabels Labels for the boxes; examples of values: Automatic, {"X", "Y", "Z"} BoxOrientation Orientation of the graph; possible values: Vertical, Horizontal BoxOutliers Whether to indicate outliers; possible values: None (whiskers are drawn to cover the

entire data set), All (outliers are shown separately), Automatic (near and far outliers can be drawn differently by using BoxOutlierMarkers) BoxOutlierMarkers Markers for the outliers; examples of values: Automatic, {Ê, Á}, {{Automatic, 10}} BoxFillingStyle Styles of the boxes; examples of values: Automatic, Hue[0], {Hue[0], Hue[1/3], Hue[2/3]} BoxLineStyle Style of all lines; examples of values: Automatic, Hue[2/3] BoxMedianStyle Additional styles for the median line; examples of values: Automatic, Thickness[Medium] BoxExtraSpacing Extra space between the boxes; examples of values: 0, 0.1

The following plots illustrate the first two forms of data mentioned previously. In the first case, we have a vector of 100 observations. In the second case, we have a matrix with 20 rows and three columns. [email protected]; data1 = [email protected]@5, 1D, 100D; data2 = [email protected]@8, 1D, 820, 3
[email protected], [email protected]< 12 20

10

:

15

8

,

>

10

6 5 4 2

1

2

3

Chapter 8 • Graphics for Data

265

A box-and-whisker plot is simply a way to show the quartiles and the minimum and maximum of the data. In the first example, these statistics are as follows: [email protected], [email protected], 0.25D, [email protected], [email protected], 0.75D, [email protected]< 81.27455, 3.39826, 4.78942, 6.52369, 12.4698<

The horizontal line inside the box is the median or the 0.5 quantile. Both below and above the median, we have 50% of the data. The bottom and top of the box are at the 0.25 and 0.75 quantiles, so inside the box we have 50% of the data. Both below and above the box, we have 0.25% of the data. The bottom and top horizontal lines of the “whiskers” are at the minimum and maximum of the data. This kind of plot gives a quick overview of the extent of a data set. For more about the statistical plots package, look at StatisticalPlotsêguideêStatisticalPlotsPackage. ‡ Example 1

As an example, consider the same barley data we investigated, by using multiway dot plots, in Section 8.4.1, p. 262: data = [email protected]"êUsersêheikkiêDocumentsêMNDataêvisdataêmodBarley", "Table"D; [email protected], AspectRatio Ø 0.4, BoxOrientation Ø Horizontal, BoxLabels Ø 8"Waseca", "Crookston", "Morris", "Univ. Farm", "Duluth", "Gr. Rapids"<, ImageSize Ø 400D Waseca

Crookston Morris

Univ. Farm Duluth

Gr. Rapids 20

30

40

50

60

‡ Example 2

A near outlier is a value beyond 1.5 times the interquantile range from the edge of the box. A far outlier is a value beyond 3 times the interquantile range. If the value of BoxOutliers is All, then all outliers are plotted in the same way; if the value is Automatic, then near and far outliers are plotted differently if so determined by the BoxOutlierMarkers option. The markers are defined in the same way as for PlotMarkers (see Section 8.1.3, p. 244). [email protected], 3, 8, 5, 2, 7, 10, 4, 3, 5, 16, 24<, BoxOutliers Ø Automatic, BoxOutlierMarkers Ø 8Ê, Á<, BoxOrientation Ø Horizontal, AspectRatio Ø 0.2, ImageSize Ø 200D Ê

5

10

15

Á

20

266

Mathematica Navigator

8.4.3 Pie Charts A pie chart illustrates how a total amount is made up from certain components. The purpose is to give the reader an impression of the relative magnitudes of the components. In the PieCharts` package: PieChart[{y1 , y2 , … }] Plot a pie chart from the positive numbers y1 , y2 , …

Options: PieLabels Labels in the wedges; examples of values: Automatic, {"A", "B", "C"} PieStyle Style(s) inside the borders of the wedges; examples of values: Automatic, Table[GrayLevel[p], {p, 0.7, 1, 0.1}] PieEdgeStyle Style of the border of the wedges; examples of values: Automatic, Thickness[Medium], Directive[Thickness[Medium], Blue] PieExploded Whether some wedges are exploded; examples of values: None, All, {4}, {4, 0.2}, {4, 5}, {{4, 0.2}, {5, 0.2}} PieOrientation Starting angle of the first wedge (the default is 0) and whether to order the wedges

counterclockwise (the default) or clockwise; examples of values: Automatic, -p/2, "Clockwise", {p/2, "Clockwise"} PieChart also has the options of Graphics. An exploded wedge is set off from the pie. A value such as {4, 0.2} defines that the fourth wedge is set off by the amount 0.2.

As an example, an algorithm was improved by four methods. Of the total savings in running time, the first method contributed 12%, the second 15%, the third 38%, and the fourth 35%. The corresponding pie chart is shown here: << PieCharts` PieChartA812, 15, 38, 35<,

PieLabels Ø 9"Method 1\n12%", "Method 2\n15%", "Method 3\n38%", "Method 4\n35%"=, PieStyle Ø [email protected]@pD, 8p, 0.65, 0.95, 0.1
Method 2 15% Method 3 38%

Method 1 12%

Method 4 35%

8.4.4 Vector Fields In the VectorFieldPlots` package: ListVectorFieldPlot[data] Plot the given array of vectors

Chapter 8 • Graphics for Data

267

data = [email protected], [email protected]<, 8i, 0, 1, 0.2<, 8j, 0, 1, 0.2
8.5 Graph Plots 8.5.1 Graph Plots ‡ Graph Plots GraphPlot[{v1 Ø v2, v3 Ø v4, … }] (Ÿ6) Connect vertices v1 and v2, … GraphPlot[{{v1 Ø v2, lb1}, {v3 Ø v4, lb2}, … }] Edges have the given labels GraphPlot[m] Plot the graph represented by the adjacency matrix m

Some options: DirectedEdges Whether to show edges as directed arrows; possible values: False (edges are

shown as lines), True, {True, "ArrowheadsSize"Ø s} VertexLabeling Whether to show vertex names as labels; examples of values: Automatic (show

labels as tooltips if the graph is small), Tooltip (show labels as tooltips), True (show labels explicitly), False (do not show labels at all), All (show labels both explicitly and as tooltips) Graphs are useful in illustrating connections and flows between points. The points are called vertices (or nodes), and the lines or arrows between the vertices are called edges. In using GraphPlot, we only indicate, by using some names for the vertices, which vertices should be connected; the coordinates of the vertices are automatically chosen by GraphPlot using some algorithms that try to obtain a clear graph. However, we can also define the coordinates with an option, if the automatic coordinates do not satisfy us. Here are simple examples of graphs: [email protected] Ø 2, 1 Ø 3, 2 Ø 3, 2 Ø 4, 3 Ø 4
c13

c34 c23

, c12

,

>

c24

By default, vertices are shown as points and edges as lines. In the previous plots, the names 1, 2, 3, and 4 of the vertices can be seen as tooltips: The name of a vertex appears when the mouse cursor is moved (without pressing the button) above the vertex. In the second plot, we have labels of edges. In the third example, we represented the graph with an adjacency matrix (the matrix can also be a sparse array; see Section 21.2.1, p. 689). Some more examples:

268

Mathematica Navigator

[email protected] Ø 2, 1 Ø 3, 2 Ø 3, 2 Ø 4, 3 Ø 4<, DirectedEdges Ø TrueD, [email protected] Ø 2, 1 Ø 3, 2 Ø 3, 2 Ø 4, 3 Ø 4<, DirectedEdges Ø 8True, "ArrowheadsSize" Ø 0.06<, VertexLabeling Ø TrueD, [email protected] Ø b, a Ø c, b Ø c, b Ø d, c Ø d<, VertexLabeling Ø TrueD< c

3

:

,

4

1

,

a

d

>

b

2

In the first plot, we have arrows. In the second plot, we have labels for the vertices and the size of the arrowheads is made larger (the size and other properties of the arrowheads can also be adjusted with the PlotStyle option; see General Options). The third plot shows that the names of the vertices can be any expression. Note that we also have the GraphData command with which we can plot and study many graphs (see Section 9.3.1, p. 301). See also CombinatoricaêguideêCombinatoricaPackage in the Documentation Center for information about the Combinatorica` package. Next, we study all the special options of GraphPlot. The options are grouped into options for edges, options for vertices, and general options. In addition to these options, we have the options of Graphics. In addition to GraphPlot, we have LayeredGraphPlot and TreePlot. These are considered later. ‡ Options for Edges DirectedEdges Whether to show edges as directed arrows; possible values: False (edges are

shown as lines), True, {True, "ArrowheadsSize"Ø s} MultiedgeStyle How to draw multiple edges between vertices; examples of values: Automatic

(multiple edges are shown; however, if the graph is defined by an adjacency matrix, multiple edges are not shown), 0.2 (the distance between the outermost edges is a fraction of 0.2 of the distance of the corresponding vertices), True (show multiple edges), False (do not show multiple edges) SelfLoopStyle How to draw edges linking a vertex to itself; examples of values: Automatic (selfloops are shown; however, if the graph is defined by an adjacency matrix, self-loops are not shown), 0.5 (the diameter of a self-loop circle is a fraction of 0.5 of the average edge length), True (show self-loops), False (do not show self-loops) EdgeLabeling Whether to include the given labels of the edges; examples of values: True (show edge labels explicitly), Automatic (show edge labels as tooltips), All (show edge labels both explicitly and as tooltips), False (do not show edge labels) EdgeRenderingFunction Function to give explicit graphics for edges; examples of values: Automatic (edges are dark red lines), None (no edges), ({Red, Arrow[#1]} &) The DirectedEdges option was explained previously. Here are examples of MultiedgeStyle: [email protected] Ø 2, 2 Ø 3, 3 Ø 2<, MultiedgeStyle Ø ÒD & êü 8Automatic, 0.5, False< :

,

With the SelfLoopStyle we can adjust the size of a circle:

,

>

Chapter 8 • Graphics for Data

269

[email protected] Ø 2, 2 Ø 3, 3 Ø 3<, SelfLoopStyle Ø ÒD & êü 8Automatic, 0.3, 1< :

,

>

,

Edge labels are normally drawn explicitly, as is shown in the first plot that follows. If the EdgeLabeling option has the value Automatic, the edge labels are only shown as tooltips. The value All causes the labels to be shown both explicitly and as tooltips.

[email protected] Ø 2, c12 <, 82 Ø 3, c23 <, 83 Ø 3, c33 <<, EdgeLabeling Ø ÒD & êü 8True, Automatic, All<

:

c12

c23

c33

,

,

c12

c23

c33

>

Edges are normally lines (as can be seen from the first plot that follows) or arrows, with the arrowhead somewhat back from the top of the arrow. If the EdgeRenderingFunction option has the value None, the edges are not drawn, as can be seen from the second plot. We can give the option a value as a pure function, where #1 refers to the list of coordinates of the vertices at the ends of an edge. (The function can also have arguments #2 and #3 that refer to the names of the vertices and to the label of the edge, respectively.) In the third plot, we ask to draw red arrows between the vertices. [email protected] Ø 2, 2 Ø 3, 3 Ø 3<, EdgeRenderingFunction Ø ÒD & êü 8Automatic, None, H8Red, [email protected]Ò1D< &L< :

,

,

>

For more about arrows, see Section 6.2.5, p. 161. Next, we adjust the arrows in various ways. In the first plot, the ends of the arrows are set back from the end points by a small amount. In the second plot, we use the Arrowheads directive to insert arrowheads at both ends of the arrows. In the third plot, we define custom size and position for the arrowheads. [email protected] Ø 2, 2 Ø 3, 3 Ø 3<, EdgeRenderingFunction Ø ÒD & êü [email protected]Ò1, 0.1D &L, [email protected], 0.05
,

,

>

‡ Options for Vertices VertexLabeling Whether to show vertex names as labels; examples of values: Automatic (show

labels as tooltips if the graph is small), Tooltip (show labels as tooltips), True (show labels explicitly), False (do not show labels at all), All (show labels both explicitly and as tooltips) VertexCoordinateRules Explicit vertex coordinates as a complete list of {x, y} pairs or as a complete or incomplete list of rules for the {x, y} pairs; examples of values: Automatic, {coordinates}, {1 Ø {0, 0}, 4 Ø {1, 0.5}} VertexRenderingFunction Function to give explicit graphics for vertices; examples of values: Automatic (vertices are blue points with tooltips showing the names), None (no vertices), ({Yellow, EdgeForm[Black], Disk[#1, 0.2], Black, Text[#2, #1]} &) (yellow disks with black edges and black labels)

270

Mathematica Navigator

The first option was explained previously. If the graph given by GraphPlot does not satisfy us, even after trying several different methods (see the Method option discussed later), we can ourselves define

the coordinates of the vertices. In the first plot that follows, we define the coordinates as a list of 9x, y= pairs. In the second plot, we define the coordinates as rules. In the third plot, we only define the coordinates of two vertices. [email protected] Ø 2, 1 Ø 3, 2 Ø 3, 2 Ø 4, 3 Ø 4<, VertexLabeling Ø True, VertexCoordinateRules Ø ÒD & êü 8880, 0<, 81, 0.5<, 81, -0.5<, 82, 0<<, 81 Ø 80, 0<, 2 Ø 81, 0.5<, 3 Ø 81, -0.5<, 4 Ø 82, 0<<, 81 Ø 80, 0<, 4 Ø 81, 0.5<<< 2

:

2

4

>

2 1

4

,

1

4

, 3

3

3

1

Note that coordinates of vertices can only be defined by rules if the Method option has the default value "SpringElectricalEmbedding". The value of the VertexRenderingFunction option can be a pure function where #1 refers to the coordinates and #2 to the label of a vertex. Here are examples of this option: [email protected] Ø 2, 2 Ø 3, 3 Ø 3<, VertexRenderingFunction Ø ÒD & êü 8Automatic, None, H8Yellow, [email protected], [email protected]Ò1, 0.2D, Black, [email protected]Ò2, Ò1D< &L< :

,

,

1

2

3

>

‡ General Options Method Method used to lay out the graph; possible values: Automatic (means "SpringElectricalEmbedding"; however, "RadialDrawing" is used for trees), "CircularEmbedding", "HighDimensionalEmbedding", "LinearEmbedding", "RandomEmbedding", "SpiralEmbedding", "SpringEmbedding", "SpringElectricalEmbedding", "LayeredDrawing", "LayeredDigraphDrawing", "RadialDrawing", {"meth", "Rotation" Ø q}

(rotate the graph q radians clockwise) PackingMethod Method used to lay out a graph with disconnected components; possible values: Automatic, "ClosestPacking", "ClosestPackingCenter", "Layered", "LayeredLeft", "LayeredTop", "NestedGrid" PlotStyle Overall graphics directives for vertices and edges; examples of values: Automatic, {Red, PointSize[Medium], Thickness[Medium], Dashed, Arrowheads[0.05]}

Each value of Method has some options. The "Rotation" option is one. Consider the following three plots: edges = 81 Ø 2, 1 Ø 3, 1 Ø 4, 1 Ø 5, 1 Ø 6, 2 Ø 7, 2 Ø 8, 3 Ø 7, 3 Ø 8, 4 Ø 7, 4 Ø 8, 5 Ø 7, 5 Ø 8, 6 Ø 7, 6 Ø 8<; vertices = 880, 2<, 82, 4<, 82, 3<, 82, 2<, 82, 1<, 82, 0<, 84, 3<, 84, 1<<;

Chapter 8 • Graphics for Data

271

[email protected], VertexLabeling Ø True, AspectRatio Ø 1D, [email protected], VertexLabeling Ø True, Method Ø 8"LayeredDigraphDrawing", "Rotation" Ø -p ê 2<, AspectRatio Ø 1D, [email protected], VertexLabeling Ø True, VertexCoordinateRules Ø vertices, AspectRatio Ø 1D< 6

:

6

4

2

5

8

4

7

3

7

>

8 5

7

,

1

,

1

4

1 3

5

2

6

8

3 2

"LayeredDigraphDrawing" method, with a rotation of -p ê 2, we get a good result. By defining the

With the default "SpringElectricalEmbedding" method, the plot is not very clear. With the

coordinates of the vertices, we get just the result we like most. (We also considered this example in Section 6.2.9, p. 174, by using our own plotting program.) The methods used by GraphPlot are explained in the Documentation Center at tutorialêGraphDrawingIntroduction and tutorialêGraphDrawing. The default method, "SpringElectricalEmbedding", is described as follows: “Invoke the spring embedding method, in which a vertex is subject to either attractive or repulsive force from another vertex, as though they are connected by a spring; the spring has an ideal length equal to the graph distance between the vertices; the total spring energy is minimized.” Note that the plot given by GraphPlot can also be adjusted manually with the mouse. Suppose that, in the second plot shown previously, we want to move the vertex 7 somewhat downwards. Just click on the graph and on the vertex 7 a sufficient number of times until the vertex 7 is selected. Then drag the vertex downwards. For more about manipulating plots with the mouse, see Section 5.1.3, p. 126. If the graph contains disconnected parts, the PackingMethod option can be used to adjust the way the graph is displayed: [email protected] Ø 2, 1 Ø 3, 2 Ø 3, 2 Ø 4, 3 Ø 4, 5 Ø 6<, PackingMethod Ø ÒD & êü 8Automatic, "ClosestPackingCenter", "NestedGrid"<

:

,

,

>

With PlotStyle, we can adjust the size of the points representing the vertices, the thickness and dashing of the edges, and the size and position of the arrowheads. In addition, we can define an overall color that is used both for the edges and for either the points representing the vertices or the text in the vertex labels. However, edge and vertex rendering functions have higher priority than plot style.

272

Mathematica Navigator

[email protected] Ø 2, 2 Ø 3, 3 Ø 3<, VertexLabeling Ø True, PlotStyle Ø RedD, [email protected] Ø 2, 2 Ø 3, 3 Ø 3<, DirectedEdges Ø True, PlotStyle Ø 8Red, [email protected], 0.8<
1

,

3

2

,

>

‡ Applications

Here is a rate diagram for a birth-death process:

[email protected] Ø 1, l0 <, 81 Ø 2, l1 <, 82 Ø 3, l2 <, 83 Ø 2, m3 <, 82 Ø 1, m2 <, 81 Ø 0, m1 <<, DirectedEdges Ø True, MultiedgeStyle Ø 0.5, VertexLabeling Ø True, ImageSize Ø 350, Epilog Ø [email protected]@". . .", 12D, 83.25, 0.03

l1 1

m1

l2 3

2 m2

...

m3

Next, we draw a graph describing the process of modeling (see Giordano, Weir, and Fox, 1997, p. 33): b1 = "Real-world data"; b2 = "Model"; b3 = "Mathematical\nconclusions"; b4 = "Predictionsê\nexplanations";

[email protected] Ø b2, "Formulation"<, 8b2 Ø b3, "Analysis"<, 8b3 Ø b4, "Interpretation"<, 8b4 Ø b1, "Test"<<, DirectedEdges Ø True, VertexLabeling Ø True, VertexCoordinateRules Ø 880, 1<, 81, 1<, 81, 0<, 80, 0<<, ImageSize Ø 200, AspectRatio Ø 0.5D Real-world data

Formulation

Analysis

Test

Predictionsê explanations

Model

Interpretation

Mathematical conclusions

Now we draw relationships between some probability distributions: :ber = [email protected], hyp = [email protected], K, ND, bin = [email protected], pD, po = [email protected], normal = "NHm, sL", gamma = [email protected], lD, sum = ‚ Xi >; n

GraphPlotA98hyp Ø bin, [email protected] ã K ê N, N Ø ¶<, CenterD<, 8bin Ø bin, sum<, 8bin Ø ber, n ã 1<, 8ber Ø bin, sum<, 8bin Ø po, [email protected] ã n p, n Ø ¶, p Ø 0<, CenterD<,

i=1

9bin Ø normal, ColumnA9m ã n p, s2 ã n p q, n Ø ¶=, CenterE=,

8po Ø po, sum<, 9po Ø normal, ColumnA9m ã l, s2 ã l, l Ø ¶=, CenterE=, 8normal Ø normal, sum<, 8gamma Ø gamma, sum<,

9gamma Ø normal, ColumnA9m ã a ê l, s2 ã a ë l2 , a Ø ¶=, CenterE==, ImageSize Ø 400, DirectedEdges Ø 8True, "ArrowheadsSize" Ø 0.02<, MultiedgeStyle Ø 0.3, SelfLoopStyle Ø 0.4, VertexLabeling Ø True, VertexCoordinateRules Ø 8hyp Ø 80, 1<, bin Ø 81, 1<, ber Ø 82, 1<, po Ø 80, 0<, normal Ø 81, 0<, gamma Ø 82, 0<
Chapter 8 • Graphics for Data

273

‚ Xi n

i =1

HypIn , K , N M

p

BinIn , p M

K N

N ض

n1 ‚ Xi

BerIp M

n

i =1

lnp

mnp

nض

s2  n p q

pØ0

nض

m

ml NHm, sL

s2  l

PoHlL ‚ Xi

lض

n

s2 

a l a l2

‚ Xi n

GHa, lL

i =1

aض

i =1

‚ Xi n

i =1

For example, the sum of n independent variables having the BerIpM distribution has the binomial distribution. The sum of n independent variables having the PoHlL distribution also has the Poisson distribution [more exactly, PoHn lL distribution]. The binomial distribution BinIn, pM can be approximated, for large n, by the normal distribution NJn p,

n p q N.

Next, we draw a social network of my wife:

relationships = 8"Marjatta" Ø "Heikki", "Marjatta" Ø "Hanna", "Hanna" Ø "Kerttu", "Hanna" Ø "BO", "Marjatta" Ø "Kerttu", "Kerttu" Ø "Raimo", "Marjatta" Ø "Eine", "Eine" Ø "Jussi", "Eine" Ø "Tuula", "Marjatta" Ø "Marjukka", "Marjukka" Ø "Antti", "Marjatta" Ø "Ilse", "Ilse" Ø "Hanna", "Marjatta" Ø "Seija", "Seija" Ø "Pirkko", "Seija" Ø "Eino"<; [email protected], VertexLabeling Ø True, ImageSize Ø 230D

Antti BO

Marjukka Ilse

Hanna Kerttu

Marjatta Eino

Seija Heikki

Pirkko Eine

Tuula Jussi

Raimo

274

Mathematica Navigator

‡ Layered Graph Plots LayeredGraphPlot[{v1 Ø v2, v3 Ø v4, … }] (Ÿ6) Connect vertices v1 and v2, … LayeredGraphPlot[{v1 Ø v2, v3 Ø v4, … }, pos] Place the dominant vertices at position pos;

possible values of pos: Top, Bottom, Left, Right This command is used in the same way as GraphPlot; edge labels can be given and the graph can be defined by an adjacency matrix. The options are almost the same as the ones of GraphPlot; the default value of DirectedEdges is now True, and the Method option does not exist. A layered graph plot shows the vertices at several layers or levels: [email protected], VertexLabeling Ø True, ImageSize Ø 260D

Marjatta

Heikki

Eine

Marjukka

Seija

Jussi

Tuula

Antti

Pirkko

Ilse

Eino

Hanna

Kerttu

BO

Raimo

If vertex coordinates are not given, some edges may be curved. If vertex coordinates are given, the edges are straight lines.

8.5.2 Tree Plots TreePlot[{v1 Ø v2, v3 Ø v4, … }] (Ÿ6) Connect vertices v1 and v2, … TreePlot[{v1 Ø v2, v3 Ø v4, … }, pos] Place the dominant vertices at position pos; possible values

of pos: Top, Bottom, Left, Right, Center TreePlot[{v1 Ø v2, v3 Ø v4, … }, pos, vk] Use vk as the root node

This command, too, is used in the same way as GraphPlot; edge labels can be given and the graph can be defined by an adjacency matrix. For TreePlot, we have the new option LayerSizeFunction with the default value (1 &) (the function defines the height of the layers), whereas the Method option does not exist. The next plot describes the dependencies of the chapters of a book: [email protected] Ø 3, 1 Ø 2, 2 Ø 4, 2 Ø 6, 4 Ø 5, 6 Ø 8<, Top, 1, VertexLabeling Ø True, LayerSizeFunction Ø H0.3 &L, ImageSize Ø 100D 1 3

2 4

6

5

8

Chapter 8 • Graphics for Data

275

In the following plot, we show methods used in modeling (see Giordano et al., 1997, p. 34): TreePlotA991 Ø 2, "Phenomenon\nof interest"=,

92 Ø 3, "Replication\nof behavior"=, 92 Ø 4, "Mathematical\nrepresentation"=, 83 Ø 5, "Simulation"<, 83 Ø 6, "Experimentation"<, 84 Ø 7, "Model selection"<, 84 Ø 8, "Model construction"<=, Left, 1,

VertexRenderingFunction Ø None, LayerSizeFunction Ø H8 &L, ImageSize Ø 350E

Model construction Mathematical representation

Model selection

Phenomenon of interest Replication of behavior

Experimentation Simulation

8.6 Plots for 3D Data 8.6.1 Plots for 3D Data ‡ Regular Data

Often, 3D data are in a form of a matrix: z11



z1 n

ª zm 1 … zm n We call such data regular: Each row has the same number of values. Also, only the z values are given; the x and y values are not given at all. Indeed, it is assumed that the z values are given for equally spaced x and y coordinates. In such a situation, we simply need to be able to tell the ranges of the x and y coordinates, and this can be done with the DataRange option, which is explained soon. In the next box, we have commands to plot regular 3D data. Irregular data are considered later. ListPlot3D[data] 3D surface plot ListPointPlot3D[data, Filling Ø Bottom] (Ÿ6) 3D points, possibly with stems BarChart3D[data] 3D bar chart (in the BarCharts` package) ArrayPlot[data] Grayscale squares MatrixPlot[data] (Ÿ6) Color squares ListDensityPlot[data] A density plot ListContourPlot[data] A contour plot

Data are given in the matrix form: {{z11 , …, z1n }, …, {zm1 , …, zmn }} (each row corresponds to a fixed value of y)

We also have GeneralizedBarChart3D (in the BarCharts` package), ListVectorFieldPlot3D (in the VectorFieldPlots` package), and ReliefPlot.

276

Mathematica Navigator

‡ Examples

To illustrate these commands, we define a very simple data set:

data1 = 880, 0, 1, 1, 0<, 81, 0, 1, 1, 1<, 82, 1, 2, 2, 1<, 82, 1, 2, 2, 2<<;

First we show six plots that have a true 3D nature. Here are three surface plots:

[email protected], BoxRatios Ø Automatic, AxesLabel Ø 8"x", "y", ""
:

,

>

,

In the first plot, the given points are connected by surface pieces and a mesh is drawn on the resulting surface. The first row {0, 0, 1, 1, 0} of the data is in front (parallel to the x axis), the second row {1, 0, 1, 1, 1} is next, and so on. In the second plot, we ask for a mesh corresponding to the data points: The points are at the corner points of the surface pieces. In the third plot, we only have the mesh lines. << BarCharts`

[email protected], BoxRatios Ø AutomaticD, [email protected], Filling Ø Bottom, BoxRatios Ø AutomaticD, BarChart3DAdata1¨, BoxRatios Ø Automatic, Ticks Ø 881, 2, 3, 4, 5<, 81, 2, 3, 4<, Automatic
2.0 1.5 : 1.0 0.5 0.0 1

2.0 1.5 , 1.0 0.5 4 0.0 3 1 2

2

3 4

5 1

>

2.0 1.5 , 1.0 4 0.5 0.0 3 2

2

3 4

5 1

4 1

3 2

3

2 4 5

1

positions of the points in the space. In the second plot, we have the vertical lines to the Ix, yM plane, and In the first plot, we have 3D points (a scatter plot). Without vertical lines, it is difficult to infer the

now the plot is much clearer. The third plot shows the points as a bar chart; this plot gives a very clear view for the data. In a bar chart, we have to transpose the data to get a plot comparable with the other plots. Note that all six 3D plots shown previously can be rotated with the mouse. Rotation dramatically improves the illusion of space. Next, we draw other kinds of plots:

Chapter 8 • Graphics for Data

277

[email protected]@data1, Mesh Ø True, Frame Ø True, FrameTicks Ø 8True, True, None, None<, DataReversed Ø TrueD, [email protected], Mesh Ø True, Frame Ø True, FrameTicks Ø 8True, True, None, None<, DataReversed Ø TrueD, [email protected], AspectRatio Ø Automatic, FrameTicks Ø 881, 2, 3, 4, 5<, 81, 2, 3, 4<, None, None
In the first plot, the values are plotted as grayscale squares, and in the second plot they are plotted as color squares. The density plot shows the data values somewhat smoothed: high values as light and low values as dark. In the contour plot, there are 10 contours that correspond to 10 equally spaced values between the minimum and maximum values. The constants that correspond to the contours can be seen by moving the mouse over the contour plot. With the option ContourLabels Ø Automatic we get some explicit labels in the plot. ‡ Options

The options of ListPlot3D, ListDensityPlot, and ListContourPlot are almost the same as the ones of Plot3D, DensityPlot, and ContourPlot. Thus, we can refer to Chapter 7 for the options. Some options, such as MaxRecursion and PlotPoints, are lacking, but we have the following new options: Common special options of ListPlot3D, ListDensityPlot, and ListContourPlot: DataRange The range of x and y values to assume for data; examples of values: Automatic, {{xmin, xmax}, {ymin, ymax}} InterpolationOrder The polynomial degree (in each variable) of surfaces used in joining data

points; default value: None MaxPlotPoints The maximum number of points to include; default value: Automatic

As stated previously, the data points contain only the z values. To plot ticks on the axes, Mathematica assumes that the x and y values are evenly spaced and are, in fact, the integers 1, 2, 3, …; you can see this from the previous plots. If the true x and y values are not these integers, the option DataRange should be used to input the true ranges within which the points lie. For example, suppose that x values are 0, 1, 2, 3, and 4 and y values 0, 2, 4, and 6; then the x range is {0, 4} and the y range is {0, 6}. We can get the correct x and y coordinates as follows: [email protected], DataRange Ø 880, 4<, 80, 6<<, ImageSize Ø 100D

278

Mathematica Navigator

The options of ListPointPlot3D are mostly the same as the ones of Graphics3D. Axes and BoxRatios now have the default values True and {1, 1, 0.4}, respectively. The following new options

are available: Special options of ListPointPlot3D: DataRange The range of x and y values to assume for data; examples of values: Automatic, {{xmin, xmax}, {ymin, ymax}} PlotStyle Style of the points; default value: Automatic ColorFunction How to determine the colors of points; default value: Automatic ColorFunctionScaling Whether to scale arguments to ColorFunction; possible values: True, False

The options of BarChart3D also are mostly the same as the ones of Graphics3D. Axes and BoxRatios now have the default values Automatic and {1, 1, 1}, respectively. The following new options are available: Special options of BarChart3D: BarEdges Whether to draw the edges of the bars; possible values: True, False BarEdgeStyle Style of the edges; default value: GrayLevel[0] BarSpacing Space between the bars in the x and y directions; default value: 0 BarStyle Style of the faces of the bars; default value: GrayLevel[1] ArrayPlot and MatrixPlot and their options are considered in Section 21.2.1, p. 690. ‡ Coloring

We used the ColorFunction option in Sections 7.5.1, p. 214, 7.5.4, p. 222, and 7.6.1, pp. 227 and 230. Now we use this option to color data plots according to the values of the data points. In BarChart3D, the colors have to be attached to each data value. data2 = [email protected]@88 i + 5 j, 10 i + 7 j
[email protected], Ticks Ø None, BoxRatios Ø 815, 10, 10<, ColorFunction Ø [email protected] - Ò3D &LD, [email protected], Ticks Ø None, BoxRatios Ø 815, 10, 10<, ColorFunction Ø [email protected] - Ò3D &LD, BarChart3DAdata3¨, BoxRatios Ø 815, 10, 10<, Ticks Ø NoneE=

:

,

,

>

Chapter 8 • Graphics for Data

279

[email protected], DataReversed Ø True, ColorFunction Ø [email protected] - ÒD &LD, [email protected], AspectRatio Ø Automatic, FrameTicks Ø None, ColorFunction Ø [email protected] - ÒD &LD, [email protected], AspectRatio Ø Automatic, ColorFunction Ø [email protected] - ÒD &L, FrameTicks Ø NoneD<

:

,

,

>

‡ Example: Galaxy

We have in a text file galaxy various data about NGC 7531, a spiral galaxy in the Northern Hemisphere. The data are, again, from Cleveland (1993) and can be found on the CD-ROM accompanying this book. data6 = [email protected]@"êUsersêheikkiêDocumentsêMNDataêvisdataêgalaxy", "Table"DD;

(Rest drops the first row, which contains the headings of the columns.) The file contains 323 rows. The first row is as follows: 83, 8.46279, -38.1732, 102.5, 39.1, 1769< data6P1T

The first item is the observation number (ranging from 3 to 417 but having missing observations), the second and third items are the coordinates of a point of the galaxy, and the sixth item is the velocity of the galaxy at the given point. We extract the columns from the data: 8no, eastwest, southnorth, slitangle, radialposition, velocity< = data6¨;

The velocity varies between the following numbers (given in kilometers per second): [email protected], [email protected]< 81409, 1775<

Then we plot the velocities. Note that the plot can be rotated with the mouse.

ListPointPlot3DA8eastwest, southnorth, velocity<¨, BoxRatios Ø 86, 10, 10<, PlotStyle Ø [email protected], ViewPoint Ø 8-2.9, 1, 1.2<, ImageSize Ø 200, AxesLabel Ø 8"sn", "ew", " velocity"
1700

1600 veloci

1500 20 sn

0

-50

-20

0 50

ew

280

Mathematica Navigator

‡ Example: Barley

In Sections 8.4.1, p. 262, and 8.4.2, p. 265, we considered barley yields data. Now we illustrate the same data with a bar chart: data4 = [email protected]"êUsersêheikkiêDocumentsêMNDataêvisdataêmodBarley", "Table"D;

sites = 8"Waseca", "Crookston", "Morris", "Univ. Farm", "Duluth", "Gr. Rapids"<; varieties = 8"Svansota", "Manchuria", "No. 475", "Glabron", "Velvet", "Peatland", "Trebi", "No. 462", "No. 457", "Wisconsin"<; xticks = [email protected], sites<¨; yticks = [email protected], varieties<¨;

xgrid = [email protected], 5.5, 1D; ygrid = [email protected], 9.5, 1D; zgrid = [email protected], 60, 10D; grids = 888-1, 0, 0<, 8ygrid, zgrid<<, 880, 1, 0<, 8xgrid, zgrid<<, 880, 0, -1<, 8xgrid, ygrid<<<;

BarChart3DAdata4¨, BoxRatios Ø 86, 10, 7<, ViewPoint Ø 81.8, -2.4, 1.6<, AxesEdge Ø 8Automatic, 81, -1<, Automatic<, Ticks Ø 8xticks, yticks, [email protected], 60, 10D<, FaceGrids Ø grids, ImageSize Ø 280E

60 50 40 30 Wiscons

20

No. 457 No. 462 Trebi Peatland Velvet

10

Waseca Crookston Morris

Glabron

Univ. Farm Duluth Gr. Rapids

No. 475 Manchuria Svansota

‡ Histograms

In the Histograms` package: Histogram3D[data] Plot the frequencies of the given raw data

With the option FrequencyData Ø True, we can plot given frequencies. << MultivariateStatistics` << Histograms` [email protected]; data = [email protected]@[email protected], 0<, 881, 0.6<, 80.6, 1<
Chapter 8 • Graphics for Data

281

[email protected], ImageSize Ø 260D 4 2 0 -2

50

0 -4 -2 0 2

See Section 30.2, p. 1011, for more information about frequencies and histograms. ‡ Irregular Data

If the data are irregular, we have to tell, in addition to the z values, the x and y values of the data points;

that is, the data is of the form 99x1 , y1 , z1 =, …, 9xn , yn , zn ==. For irregular data, the following commands presented

previously

still

work:

ListPlot3D,

ListPointPlot3D,

ListDensityPlot,

and

ListContourPlot. However, BarChart3D, ArrayPlot, and MatrixPlot are no longer available. In

addition, we have the following new commands: ListSurfacePlot3D[data] (Ÿ6) Find a surface that approximates the given points TriangularSurfacePlot[data] Plot a triangular surface plot according to the Delaunay triangula-

tion (in the ComputationalGeometry` package) To illustrate plots of irregular data, we first generate such data: [email protected]; data5 = [email protected] = [email protected], p
Here are some surface plots: << ComputationalGeometry`

282

Mathematica Navigator

[email protected]@data5, BoxRatios Ø Automatic, AxesLabel Ø 8"x", "y", ""
If we use Mesh Ø All in ListPlot3D, we see the triangularization of the surface, although the surface is colored smoothly. With TriangularSurfacePlot we get a surface consisting of triangles. ListSurfacePlot3D finds a surface that approximates the points. For more information about the computational geometry package, see ComputationalGeometryêguideêComputationalGeometryPackage. Next, we show two scatter plots and a density and contour plot. The second plot shows how easy it is to plot points with Graphics3D. [email protected] [email protected], Filling Ø Bottom, BoxRatios Ø Automatic, Ticks Ø NoneD, [email protected], [email protected], [email protected], Black, [email protected]ÒP1T, ÒP2T, 0<, Ò
With ListContourPlot3D we can plot surfaces of constant value; see ContourPlot3D in Section 5.4.2, p. 149.

9 Data Introduction 283 9.1 Chemical and Physical Data 284 9.1.1 Element, Chemical, and Isotope Data 284 ElementData, ChemicalData, IsotopeData 9.1.2 Particle and Astronomical Data 291 ParticleData, AstronomicalData 9.2 Geographical and Financial Data 293 9.2.1 Country and City Data 293 CountryData, CityData 9.2.2 Financial Data 299 FinancialData 9.3 Mathematical and Other Data 300 9.3.1 Mathematical Data 300 PolyhedronData, GraphData, LatticeData, KnotData 9.3.2 Word Data 303 WordData, DictionaryLookup 9.3.3 Color Data 304 ColorData 9.3.4 Example Data 308 ExampleData

Introduction Laplace was once asked who was the greatest mathematician in Germany. He replied “Pfaff.” “But what about Gauss?” asked the questioner. “Gauss,” said Laplace, “is the greatest mathematician in the world.” New in Mathematica 6 are built-in data over various fields. Here is a list of the data sets with short descriptions: Chemical data: • ElementData: bulk, atomic, chemical, etc. properties of chemical elements • ChemicalData: structural, physical, and other properties of chemical compounds • IsotopeData: static and decay properties of all nuclear isotopes Physical data: • ParticleData: properties of stable, unstable, and resonance particles • AstronomicalData: properties of stars, planets, and other objects Geographical data: • CountryData: many categories of data about countries, groups, etc. • CityData: properties of cities throughout the world Financial data: • FinancialData: current and historical stock, fund, index, currency, etc. data

284

Mathematica Navigator

Mathematical data: • PolyhedronData: geometry and properties of polyhedra • GraphData: properties of named and enumerated graphs • LatticeData: properties of named lattices • KnotData: properties of enumerated knots Word data: • WordData: properties of words and network of relations between them • DictionaryLookup: use string patterns to look up words in the dictionary Color data: • ColorData: various color schemes such as gradients Example data: • ExampleData: many types of standard test and example data Here, we can only give short introductions to these data sets. If you are interested in a particular data set, please look at the corresponding document from Help @ Documentation Center. Note that we also have the following physical packages: • PhysicalConstants`, Units` (see Section 12.1.3, p. 402) • StandardAtmosphere`, ResonanceAbsorptionLines`, BlackBodyRadiation`, Geodesy` Regarding mathematics, note the following packages: • PolyhedronOperations`, Polytopes` • GraphUtilities`, Combinatorica`, ComputationalGeometry` See guideêDatabaseConnectivity and DatabaseLinkêtutorialêOverview in the Documentation Center for tools to work with databases.

9.1 Chemical and Physical Data 9.1.1 Element, Chemical, and Isotope Data ‡ ElementData ElementData[] (Ÿ6) Give a list of all standard chemical elements sorted by atomic number ElementData[n] Give the full name of the nth element ElementData[patt] Give a list of all elements matching the string pattern ElementData["Properties"] Give a list of all properties ElementData["elem", "prop"] Give the value of the property for the element ElementData["elem", "prop", "Units"] Give the units of the property ElementData["elem", "prop", "ann"] Give the specified annotation ElementData["Classes"] Give a list of all classes ElementData["class"] Give a list of elements in the given class ElementData["elem", "class"] Give True if elem belongs to class

An element can be specified by the full name such as "Iron", by the abbreviation such as "Fe", or by the atomic number such as 26.

Chapter 9 • Data

285

Typical annotations include "Units", "UnitsName", "UnitsStandardName", "UnitsNotation", "Description", "LongDescription", "Interval" (uncertainty), and "Note".

Here are all the elements, properties, and classes: [email protected]@D, 6D

9Hydrogen, Helium, Lithium, Beryllium, Boron, Carbon, Nitrogen, Oxygen, Fluorine, Neon, Sodium, Magnesium, Aluminum, Silicon, Phosphorus, Sulfur, Chlorine, Argon, Potassium, Calcium, Scandium, Titanium, Vanadium, Chromium, Manganese, Iron, Cobalt, Nickel, Copper, Zinc, Gallium, Germanium, Arsenic, Selenium, Bromine, Krypton, Rubidium, Strontium, Yttrium, Zirconium, Niobium, Molybdenum, Technetium, Ruthenium, Rhodium, Palladium, Silver, Cadmium, Indium, Tin, Antimony, Tellurium, Iodine, Xenon, Cesium, Barium, Lanthanum, Cerium, Praseodymium, Neodymium, Promethium, Samarium, Europium, Gadolinium, Terbium, Dysprosium, Holmium, Erbium, Thulium, Ytterbium, Lutetium, Hafnium, Tantalum, Tungsten, Rhenium, Osmium, Iridium, Platinum, Gold, Mercury, Thallium, Lead, Bismuth, Polonium, Astatine, Radon, Francium, Radium, Actinium, Thorium, Protactinium, Uranium, Neptunium, Plutonium, Americium, Curium, Berkelium, Californium, Einsteinium, Fermium, Mendelevium, Nobelium, Lawrencium, Rutherfordium, Dubnium, Seaborgium, Bohrium, Hassium, Meitnerium, Darmstadtium, Roentgenium, Ununbium, Ununtrium, Ununquadium, Ununpentium, Ununhexium, Ununseptium, Ununoctium=

[email protected]@"Properties"D, 6D

9Abbreviation, AbsoluteBoilingPoint, AbsoluteMeltingPoint, AdiabaticIndex, AllotropeNames, AllotropicMultiplicities, AlternateNames, AlternateStandardNames, AtomicNumber, AtomicRadius, AtomicWeight, Block, BoilingPoint, BrinellHardness, BulkModulus, CASNumber, Color, CommonCompoundNames, CovalentRadius, CriticalPressure, CriticalTemperature, CrustAbundance, CrystalStructure, CuriePoint, DecayMode, Density, DiscoveryCountries, DiscoveryYear, ElectricalConductivity, ElectricalType, ElectronAffinity, ElectronConfiguration, ElectronConfigurationString, Electronegativity, ElectronShellConfiguration, FusionHeat, GasAtomicMultiplicities, Group, HalfLife, HumanAbundance, IconColor, IonizationEnergies, IsotopeAbundances, KnownIsotopes, LatticeAngles, LatticeConstants, Lifetime, LiquidDensity, MagneticType, MassMagneticSusceptibility, MeltingPoint, Memberships, MeteoriteAbundance, MohsHardness, MolarMagneticSusceptibility, MolarVolume, Name, NeelPoint, NeutronCrossSection, NeutronMassAbsorption, OceanAbundance, Period, Phase, PoissonRatio, QuantumNumbers, Radioactive, RefractiveIndex, Resistivity, ShearModulus, SolarAbundance, SoundSpeed, SpaceGroupName, SpaceGroupNumber, SpecificHeat, StableIsotopes, StandardName, SuperconductingPoint, ThermalConductivity, ThermalExpansion, UniverseAbundance, Valence, VanDerWaalsRadius, VaporizationHeat, VickersHardness, VolumeMagneticSusceptibility, YoungModulus=

[email protected]@"Classes"D, 6D

9Actinide, AlkaliMetal, AlkalineEarthMetal, Antiferromagnetic, Conductor, Diamagnetic, Ferromagnetic, Gas, Halogen, Insulator, Lanthanide, Liquid, Metal, Metalloid, Natural, NobleGas, Nonmetal, Paramagnetic, PoorMetal, Radioactive, Semiconductor, Solid, Stable, Synthetic, TransitionMetal=

Length êü [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 8118, 86, 22<

In the Documentation Center, under ElementData, the properties are classified as follows: basic properties, material, thermodynamic, electromagnetic and optical, abundance, periodic table, basic chemical, crystallographic, atomic, nuclear, names-related, and historical and commercial properties. A property that is not applicable to an element has the value Missing["NotApplicable"]. A property that is not available for an element has the value Missing["NotAvailable"]. A property that is unknown for an element has the value Missing["Unknown"]. ‡ Example 1

An element can be specified by standard name, abbreviation, or atomic number: [email protected]"Fe", "StandardName"D Iron [email protected]"Iron", "Abbreviation"D Fe [email protected]"Iron", "AtomicNumber"D 26

Any of these specifications can be used when asking for properties: [email protected]"Iron", "Density"D 7874. [email protected]"Fe", "Density"D 7874.

286

Mathematica Navigator

[email protected], "Density"D 7874.

An element is found in Finland: 8Finland<

[email protected]"Yttrium", "DiscoveryCountries"D

[email protected]"Yttrium", "DiscoveryYear"D 1794

Find all elements beginning with H: 8Hydrogen, Helium, Holmium, Hafnium, Hassium< [email protected]"H*"D

Ask for some annotations: [email protected]"Fe", "Density", "Units"D KilogramsPerCubicMeter [email protected]"Fe", "Density", "UnitsName"D kilograms per cubic meter [email protected]"Fe", "Density", "UnitsNotation"D kgêm3 [email protected]"Fe", "Density", "LongDescription"D density at standard temperature and pressure

Consider the class of liquids: 8Bromine, Mercury<

[email protected]"Liquid"D

[email protected]"Bromine", "Liquid"D True ‡ Example 2

Here are all boiling points:

[email protected] = [email protected]@n, "BoilingPoint"D, 8n, 118
9-252.87, -268.93, 1342., 2470., 4000., 4027., -195.79, -182.9, -188.12, -246.08, 883., 1090., 2519., 2.9 μ 103 , 280.5, 444.72, -34.04, -185.8, 759., 1484., 2830., 3287., 3407., 2671., 2061., 2861., 2927., 2913., 2927., 907., 2204., 2820., 614., 685., 59., -153.22, 688., 1382., 3345., 4409., 4744., 4639., 4265., 4150., 3695., 2963., 2162., 767., 2072., 2602., 1587., 988., 184.3, -108., 671., 1870., 3464., 3360., 3290., 3.1 μ 103 , 3.0 μ 103 , 1803., 1527., 3250., 3230., 2567., 2700., 2868., 1950., 1196., 3402., 4603., 5458., 5555., 5596., 5012., 4428., 3825., 2856., 356.73, 1473., 1749., 1564., 962., [email protected], -61.7, [email protected], 1737., 3200., 4820., 4000., 3927., 4.0 μ 103 , 3230., 2011., 3110., [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]=

Many items are missing or unknown; nevertheless, we can plot the data:

Chapter 9 • Data

287

[email protected], Mesh Ø All, ImageSize Ø 200D

5000 4000 3000 2000 1000

20

40

60

80

List all the melting points:

t2 = [email protected]@n, "MeltingPoint"D, 8n, 118
Plot pairs of boiling points and melting points:

ListPlotA8t1, t2<¨, AxesLabel Ø 8"Boiling", "Melting"<, ImageSize Ø 200E Melting 3500 3000 2500 2000 1500 1000 500 Boiling 1000

2000

3000

4000

5000

We can assign a tooltip for each point that gives the abbreviation of the element: t1t2 = [email protected]@[email protected], "BoilingPoint"D, [email protected], "MeltingPoint"D<, [email protected], "Abbreviation"DD, 8n, 118
By moving the mouse over the points in the following plot, we can see the abbreviations: [email protected], ImageSize Ø 300D

288

Mathematica Navigator

‡ Example 3

Prepare a table of boiling and melting points of all alkaline earth metals:

t = 8Ò, [email protected]Ò, "BoilingPoint"D, [email protected]Ò, "MeltingPoint"D< & êü [email protected]"AlkalineEarthMetal"D 98Beryllium, 2470., 1287.<, 8Magnesium, 1090., 650.<, 8Calcium, 1484., 842.<, 8Strontium, 1382., 777.<, 8Barium, 1870., 727.<, 9Radium, 1737., 7.0 μ 102 ==

Text ü [email protected], TableHeadings Ø 8None, 8"Element", "Boiling point", "Melting point"<
Element

Boiling point Melting point

Beryllium Magnesium Calcium Strontium Barium

2470. 1090. 1484. 1382. 1870.

1287. 650. 842. 777. 727.

Radium

1737.

7.0 μ 10

2

‡ Example 4

In the following example, some data are missing:

t = 8Ò, [email protected]Ò, "BoilingPoint"D, [email protected]Ò, "MeltingPoint"D< & êü [email protected]"NobleGas"D 88Helium, -268.93, [email protected]<, 8Neon, -246.08, -248.59<, 8Argon, -185.8, -189.3<, 8Krypton, -153.22, -157.36<, 8Xenon, -108., -111.8<, 8Radon, -61.7, -71.<, 8Ununoctium, [email protected], [email protected]<<

Before tabulating the data, we can delete all missing items: t1 = [email protected], 8_, _, _Missing
88Neon, -246.08, -248.59<, 8Argon, -185.8, -189.3<, 8Krypton, -153.22, -157.36<, 8Xenon, -108., -111.8<, 8Radon, -61.7, -71.<< Text ü [email protected]@t1, 8"Element", "Boiling point", "Melting point"
Element

Boiling point

Melting point

Neon Argon Krypton Xenon Radon

-246.08 -185.8 -153.22 -108. -61.7

-248.59 -189.3 -157.36 -111.8 -71.

‡ ChemicalData ChemicalData is used in the same way as ElementData: ChemicalData[] (Ÿ6) Give a list of all available chemicals in order of increasing molecular weight ChemicalData["chem"] Give a structure diagram for the chemical ChemicalData[patt] Give a list of all chemicals matching the string pattern ChemicalData["Properties"] Give a list of all properties ChemicalData["chem", "prop"] Give the value of the property for the chemical ChemicalData["chem", "prop", "Units"] Give the units of the property

Chapter 9 • Data

289

p p y ChemicalData["chem", "prop", "ann"] Give the specified annotation ChemicalData["Classes"] Give a list of all classes ChemicalData["class"] Give a list of chemicals in the given class ChemicalData["chem", "class"] Give True if chem belongs to class ChemicalData[{"elem", "Compound"}] Give a list of available chemicals that contain the given

element Typical annotations include "Units", "UnitsName", "UnitsStandardName", "UnitsNotation", "Description", "LongDescription", "Interval" (uncertainty), and "Note".

Here are sizes of some lists:

Length êü [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 818 179, 68, 20<

Some properties of the aspirin are as follows: [email protected]"Aspirin"D H O

O

O

O

[email protected]"Aspirin", "MoleculePlot"D

[email protected]"Aspirin", "FormulaString"D C9H8O4 82-HAcetyloxyLBenzoicAcid, AcetylsalicylicAcid, 2-AcetoxybenzoicAcid, Acenterine, Acetosal<

[email protected]"Aspirin", "AlternateStandardNames"D

Ask for chemicals that contain gold:

[email protected]"Gold", "Compound"
8Gold, á13à, BisHPropane-1, … o-CLAurateH1-LD<

Here are chemicals whose names begin with J:

290

Mathematica Navigator

8Jasmone, Jacobine, Javanicin, Jervine, Julolidine, Juglone, JunipericAcid, JanusGreenB, Josamycin< [email protected]"J*"D

Consider the melting points:

t = [email protected]@Ò, "MeltingPoint"D & êü [email protected], _MissingD; [email protected], [email protected]<

8-259.14, 3550.<

Plot a part of the frequency distribution of the melting points:

[email protected], 500, 10D, [email protected], 8-265, 505, 10
‡ IsotopeData IsotopeData[] (Ÿ6) Give a list of all known isotopes sorted by atomic number and mass number IsotopeData["elem"] Give the known isotopes of the element IsotopeData[patt] Give a list of all isotopes matching the string pattern IsotopeData["Properties"] Give a list of all properties IsotopeData["isot", "prop"] Give the value of the property for the isotope IsotopeData["isot", "prop", "Units"] Give the units of the property IsotopeData["isot", "prop", "ann"] Give the specified annotation IsotopeData["Classes"] Give a list of all classes IsotopeData["class"] Give a list of isotopes in the given class IsotopeData["isot", "class"] Give True if isot belongs to class

Typical annotations include "Units", "UnitsName", "UnitsStandardName", "UnitsNotation", "Description", "LongDescription", "Interval" (uncertainty), and "Note".

Here are sizes of some lists:

Length êü [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 83182, 33, 47<

Chapter 9 • Data

291

Isotopes of uranium are as follows:

[email protected]"Uranium"D êê Short

8Uranium217, á24à, Uranium242<

Isotopes can be referred to in several ways: [email protected]"Uranium217", "Lifetime"D 0.038 [email protected]"U217", "Lifetime"D 0.038 [email protected], 217<, "Lifetime"D 0.038

9.1.2 Particle and Astronomical Data ‡ ParticleData ParticleData[] (Ÿ6) Give a list of all known particles sorted by mass ParticleData[patt] Give a list of all particles matching the string pattern ParticleData["Properties"] Give a list of all properties ParticleData["part", "prop"] Give the value of the property for the particle ParticleData[{"part", q}, "prop"] Give the value of the property for the particle with charge q ParticleData["part", "prop", "Units"] Give the units of the property ParticleData["part", "prop", "ann"] Give the specified annotation ParticleData["Classes"] Give a list of all classes ParticleData["class"] Give a list of isotopes in the given class ParticleData["part", "class"] Give True if part belongs to class

Typical annotations include "Units", "UnitsName", "UnitsStandardName", "UnitsNotation", "Description", "LongDescription", "Interval" (uncertainty), and "Note".

Here are sizes of some lists:

Length êü [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 81002, 35, 24<

The mass of electron is as follows: [email protected]"Electron", "Mass"D 0.51099892 [email protected]"Electron", "Mass", "Units"D MegaelectronVoltsPerSpeedOfLightSquared ‡ AstronomicalData AstronomicalData has information about planets, stars, galaxies, etc. AstronomicalData[] (Ÿ6) Give a list of all available astronomical objects AstronomicalData["tag"] Give the standardized name or list of names of tag AstronomicalData[patt] Give a list of all objects matching the string pattern

292

Mathematica Navigator

AstronomicalData["Properties"] Give a list of all properties AstronomicalData["obj", "prop"] Give the value of the property for the object AstronomicalData["obj", "prop", "Units"] Give the units of the property AstronomicalData["obj", "prop", "ann"] Give the specified annotation AstronomicalData["obj", "Image"] Give a picture of the object AstronomicalData["obj", "ObjectType"] Give the basic type of the object AstronomicalData["Classes"] Give a list of all classes AstronomicalData["class"] Give a list of objects in the given class AstronomicalData["obj", "Classes"] Give the classes in which obj occurs AstronomicalData["obj", "class"] Give True if obj belongs to class

Typical annotations include "Units", "UnitsName", "UnitsStandardName", "UnitsNotation", "Description", "LongDescription", and "Note".

Possible object types are as follows:

[email protected]@Ò, "ObjectType"D & êü [email protected]

8BrightHIIRegion, DwarfPlanet, Galaxy, GlobularCluster, Nebula, OpenCluster, Planet, PlanetaryMoon, PlanetaryNebula, Star, [email protected]<

Here are sizes of some lists:

Length êü [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 8100 910, 71, 48<

Here are planets: 8Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto< [email protected]"Planet"D

Pluto is considered to be a dwarf planet: [email protected]"Pluto", "ObjectType"D DwarfPlanet

The classes and picture of sun are as follows: 8Star, MainSequenceStar, ClassGStar, StarNearest100, StarBrightest100, StarNearest10, StarBrightest10< [email protected]"Sun", "Classes"D

[email protected]"Sun", "Image"D

We have 162 planetary moons:

[email protected]"PlanetaryMoon"D êê Length

162

Chapter 9 • Data

293

Consider the density and radius of them (many of these data are missing): t = [email protected]@Ò, "Density"D, [email protected]Ò, "Radius"D<, [email protected]Ò, "Name"DD & êü [email protected]"PlanetaryMoon"D;

By moving the mouse over the points in the following plot, we can see the names of the moons: [email protected], PlotRange Ø All, ImageSize Ø 280D

9.2 Geographical and Financial Data 9.2.1 Country and City Data ‡ CountryData CountryData[] (Ÿ6) Give a list of all ordinary countries and dependencies CountryData["tag"] Give the standardized name or list of names of the tag CountryData["Properties"] Give a list of all properties CountryData["tag", "prop"] Give the value of the property for the tag CountryData["tag", {"prop", y}] Give the value of the property for year y CountryData["tag", {"prop", All}] All available years CountryData["tag", {"prop", {y1, y2}}] Years from y1 to y2 CountryData["tag", {{"prop", "curr"}, y}] Give values in currency "curr" CountryData["tag", "prop", "Units"] Give the units of the property CountryData["tag", "prop", "ann"] Give the specified annotation CountryData["tag", "Shape"] Give the shape of the tag CountryData["class"] Give a list of tags in the given class; possible classes: "Countries"

(ordinary countries and dependencies), "Groups" (groups of countries), "Continents", "Oceans" CountryData["tag", "Classes"] Give the classes and groups in which tag appears CountryData["tag", "class"] Give True if tag belongs to the given class or group

Special values of the currency "curr" are as follows:

294

Mathematica Navigator

"USDollars": nominal value in U.S. dollars (the default) "Local": nominal value in local currency "Adjusted": adjusted to give a real value in current U.S. dollars "AdjustedLocal": adjusted to give a real value in current local currency

Typical annotations include "Units", "UnitsName", "UnitsStandardName", "UnitsNotation", "Description", "Date", "DateValue", and "Note".

Here are numbers of countries and other tags:

Length êü [email protected], [email protected]"Groups"D, [email protected]"Continents"D, [email protected]"Oceans"D, [email protected]"Properties"D< 8237, 305, 7, 5, 220<

‡ Example 1

As an example, here are some properties of Finland:

[email protected]"Finland", ÒD & êü 8"Shape", "Flag", "NativeName", "IndependenceYear"<

:

,

, Suomi, 1917>

Here is a link to a web satellite image for Finland: [email protected]"Finland", "CenterLocationLink"D

http:êêmaps.google.comêmaps?q=+64+26&z=6&t=h We plot the GDP (real value in current local currency) of Finland: [email protected] [email protected]"Finland", 88"GDP", "LocalAdjusted"<, All
Chapter 9 • Data

295

‡ Example 2

Properties of the G8 countries: 8Canada, France, Germany, Italy, Japan, Russia, UnitedKingdom, UnitedStates< [email protected]"G8"D

[email protected]"G8", "Population"D

93.22682 μ 107 , 6.23121 μ 107 , 8.26892 μ 107 , 5.80927 μ 107 , 1.28085 μ 108 , 1.43202 μ 108 , 5.96678 μ 107 , 2.98213 μ 108 =

Find the 10 largest populations: Reverse ü [email protected] [email protected]@ÒD, [email protected]Ò, "Population"D< & êü [email protected], LastD, -10D êê TableForm China

1.29299 μ 109

India

1.10337 μ 109

UnitedStates 2.98213 μ 108 Indonesia

2.22781 μ 108

Brazil

1.86405 μ 108

Pakistan

1.57935 μ 108

Russia

1.43202 μ 108

Bangladesh

1.41822 μ 108

Nigeria

1.3153 μ 108

Japan

1.28085 μ 108

Show infant mortatility fraction against literacy fraction: [email protected]@[email protected]Ò, "LiteracyFraction"D, [email protected]Ò, "InfantMortalityFraction"D<, [email protected]ÒDD & êü [email protected], ImageSize Ø 420D

296

Mathematica Navigator

‡ Example 3

Plot the world: [email protected]@Green, 0.6D, [email protected]Ò, 8"SchematicPolygon", "Mollweide"
Show the name of each country by a tooltip: [email protected]@Orange, 0.1D, [email protected], [email protected]@Ò, 8"SchematicPolygon", "Mollweide"
Note that in addition to CountryData, we also have the WorldPlot` package.

Chapter 9 • Data

297

‡ CityData CityData contains information about more than 160,000 cities: CityData[] (Ÿ6) Give a list of all cities in the world sorted by population CityData["city"] Give a list of the full specifications of cities with the given name CityData[{"city", "country"}] Give a list of the full specifications of cities with the given name

in the given country CityData["Properties"] Give a list of all properties CityData["city", "prop"] Give the value of the property for the given city CityData[{"city", "region", "country"}, "prop"] Give the value of the property for the given

city in the given region of the given country CityData["city", "prop", "Units"] Give the units of the property CityData["city", "prop", "ann"] Give the specified annotation CityData[{All, "country"}] Give a list of all available cities in the given country CityData[{Large, "country"}] Give a list of all large cities in the given country CityData[{All, "region", "country"}] Give a list of all available cities in the given region of the

given country CityData[{Large, "region", "country"}] Give a list of all large cities in the given region of the

given country Typical annotations include "Units", "UnitsName", "UnitsStandardName", "UnitsNotation", "Description", "Date", and "Note".

Here are sizes of some lists:

Length êü [email protected], [email protected]"Properties"D< 8163 428, 14<

We have several cities with the name Paris: [email protected]@"Paris"D, 7D

88Paris, IleDeFrance, France<, 8Paris, Texas, UnitedStates<, 8Paris, Ontario, Canada<, 8Paris, Tennessee, UnitedStates<, 8Paris, Kentucky, UnitedStates<, 8Paris, Illinois, UnitedStates<, 8Paris, Maine, UnitedStates<, 8Paris, NewYork, UnitedStates<, 8Paris, Arkansas, UnitedStates<, 8Paris, Wisconsin, UnitedStates<, 8Paris, Missouri, UnitedStates<, 8ParisGrant, Wisconsin, UnitedStates<, 8Paris, Idaho, UnitedStates<<

[email protected]"Paris", "Population"D 2 138 551 [email protected]"Paris", "Ontario", "Canada"<, "Population"D 10 437

The 10 cities with the largest populations: 88Beijing, Beijing, China<, 8Shanghai, Shanghai, China<, 8Bombay, Maharashtra, India<, 8Karachi, Sind, Pakistan<, 8BuenosAires, BuenosAires, Argentina<, 8Delhi, Delhi, India<, 8Manila, Manila, Philippines<, 8Moscow, Moscow, Russia<, 8Seoul, SoulTvkpyolsi, SouthKorea<, 8SaoPaulo, SaoPaulo, Brazil<< [email protected]@D, 10D

298

Mathematica Navigator

[email protected]ÒP1T, [email protected]Ò, "Population"D< & êü %D Beijing Shanghai Bombay Karachi BuenosAires Delhi Manila Moscow Seoul SaoPaulo

14 930 000 14 608 512 12 691 836 11 624 219 11 574 205 10 927 986 10 444 527 10 381 222 10 349 312 10 021 295

Here is a link to a map of Bombay: [email protected]"Bombay", "LocationLink"D http:êêmaps.google.comêmaps?q=+18.96+72.82&z=12&t=h

The next plot shows the largest cities of India: [email protected]@Green, 0.4D, [email protected]"India", "Polygon"D, [email protected], [email protected], [email protected] [email protected]@[email protected]@Ò, "Coordinates"DDD, [email protected]Ò, "Name"DD & êü [email protected], "India"
Chapter 9 • Data

299

9.2.2 Financial Data FinancialData[] (Ÿ6) Give a list of all financial instruments sorted by ticker symbols FinancialData[patt] Give a list of entities matching the string pattern FinancialData["name"] Give the last known price or value of the financial entity FinancialData["name", {start}] Give a list of dates and daily closing values from start FinancialData["name", {start, end}] Give a list of dates and daily closing values from start to end FinancialData["name", {start, end, period}] Give a list of dates and prices for the specified

periods ("Day", "Week", "Month", "Year") lying between start and end FinancialData["Properties"] Give a list of all properties FinancialData["name", "prop"] Give the value of the property for the entity FinancialData["name", "prop", {start, end, … }] Give a list of dates and values of the property

for a sequence of dates or periods FinancialData["name", "prop", …, "Value"] Give the value FinancialData["name", "prop", …, "DateValue"] Give a list of date and value FinancialData["name", "prop", …, "Units"] Give the units of the property FinancialData["name", "prop", …, "ann"] Give the specified annotation FinancialData["Classes"] Give a list of all available classes FinancialData["class"] Give a list of entities in the given class

Typical annotations include "Units", "UnitsName", "UnitsStandardName", "UnitsNotation", "Description", "LongDescription", and "Currency".

Here are sizes of some lists:

Length êü [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 8186 127, 71, 8<

Here are the various classes of financial entities: 8Currencies, Exchanges, ExchangeTradedFunds, Futures, Indices, MutualFunds, Sectors, Stocks< [email protected]"Classes"D

Next, we show financial entities beginning with NASDAQ:AA: 8NASDAQ:AACC, NASDAQ:AAME, NASDAQ:AANB, NASDAQ:AAON, NASDAQ:AAPL, NASDAQ:AATI, NASDAQ:AATK, NASDAQ:AAUK, NASDAQ:AAWW< [email protected]"NASDAQ:AA*"D

Here, NASDAQ : AAPL is the Apple company: [email protected]"NASDAQ:AAPL", "Name"D Apple Inc

Ask the current value: [email protected]"NASDAQ:AAPL"D 169.26

Plot the value from 2004 on:

300

Mathematica Navigator

[email protected]@"NASDAQ:AAPL", 82004
150

100

50

0 2004

2005

2006

2007

Find the current exchange rate between euros and U.S. dollars: [email protected]"EURêUSD"D 1.4205

9.3 Mathematical and Other Data 9.3.1 Mathematical Data ‡ PolyhedronData PolyhedronData[] (Ÿ6) Give a list of all available polyhedra PolyhedronData[n] Give a list of all polyhedra with n faces PolyhedronData[patt] Give a list of all polyhedra matching the string pattern PolyhedronData["poly"] Give an image of the given polyhedron PolyhedronData["Properties"] Give a list of all properties available PolyhedronData["poly", "prop"] Give the value of the property for the polyhedron PolyhedronData["prop", "ann"] Give an annotation of the property PolyhedronData["Classes"] Give a list of all classes available PolyhedronData["class"] Give a list of the polyhedra in the given class PolyhedronData["poly","Classes"] Give the classes in which poly occurs PolyhedronData["poly","class"] Give True if poly belongs to class

Typical annotations include "Description", "LongDescription", and "Note". Here are sizes of some lists:

Length êü [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 8147, 85, 27<

All Platonic polyhedra are as follows: 8Cube, Dodecahedron, Icosahedron, Octahedron, Tetrahedron< [email protected]"Platonic"D

Chapter 9 • Data

301

Ask for some properties of a dodecahedron:

[email protected]@"Dodecahedron"D, ImageSize Ø 70D, [email protected]"Dodecahedron", "NetImage"D, [email protected]"Dodecahedron", "Volume"D<

:

1 ,

,

15 + 7

5

>

4

[email protected]"Volume", "LongDescription"D enclosed volume assuming unit smallest edge length ‡ GraphData GraphData[] (Ÿ6) Give a list of all standard named graphs GraphData[All] Give a list of all available graphs GraphData[n] Give a list of all named graphs with n vertices GraphData[patt] Give a list of all graphs matching the string pattern GraphData["graph"] Give an image of the graph GraphData["Properties"] Give a list of all properties available GraphData["graph", "prop"] Give the value of the property for the graph GraphData[{n, i}, … ] Give data for ith simple graph with n vertices GraphData[{"type", id}, … ] Give data for the graph of type with identifier id GraphData["prop", "ann"] Give an annotation of the property GraphData["Classes"] Give a list of all classes available GraphData["class"] Give a list of the graphs in the given class GraphData["class", n] Give a list of graphs with n vertices in the given class GraphData["graph", "Classes"] Give the classes in which graph occurs GraphData["graph", "class"] Give True if graph belongs to class

Typical annotations include "Description", "LongDescription", and "Note". Here are sizes of some lists: Length êü [email protected], [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 8735, 1939, 121, 71<

Ask for some properties of the cuboctahedral graph:

[email protected]@"CuboctahedralGraph"D, ImageSize Ø 80D, [email protected]"CuboctahedralGraph", "VertexCount"D, [email protected]"CuboctahedralGraph", "EdgeCount"D<

:

, 12, 24>

302

Mathematica Navigator

For graphs, look also at CombinatoricaêtutorialêCombinatorica in the Documentation Center. Also remember that we have GraphPlot (see Section 8.5, p. 267). ‡ LatticeData LatticeData[] (Ÿ6) Give a list of classical named lattices LatticeData[n] Give a list of named lattices of dimension n LatticeData[patt] Give a list of all lattices matching the string pattern LatticeData["Properties"] Give a list of all properties available LatticeData["lattice", "prop"] Give the value of the property for the lattice LatticeData[{"type", id}, … ] Give data for the lattice of type with identifier id LatticeData["Classes"] Give a list of all classes available LatticeData["class"] Give a list of the graphs in the given class LatticeData["lattice", "Classes"] Give the classes in which lattice occurs LatticeData["lattice", "class"] Give True if lattice belongs to class

Here are sizes of some lists:

Length êü [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 821, 37, 8<

As an example, here is the body-centered cubic lattice: [email protected]@"BodyCenteredCubic", "Image"D, ImageSize Ø 140D

‡ KnotData KnotData[] (Ÿ6) Give a list of classical named knots KnotData[All] Give a list of knots that have Alexander-Briggs notations KnotData["knot"] Give an image of the knot KnotData["Properties"] Give a list of all properties available KnotData["knot", "prop"] Give the value of the property for the knot KnotData[{"type", id}, … ] Give data for the knot of type with identifier id KnotData["Classes"] Give a list of all classes available KnotData["class"] Give a list of the knots in the given class KnotData["knot", "Classes"] Give the classes in which knot occurs KnotData["knot", "class"] Give True if knot belongs to class

Chapter 9 • Data

303

Here are sizes of some lists:

Length êü [email protected], [email protected], [email protected]"Properties"D, [email protected]"Classes"D< 86, 250, 63, 14<

Classical knots are as follows: 8Unknot, Trefoil, FigureEight, SolomonSeal, Stevedore, PerkoPair< [email protected]

Here are their images (we do not have an image for PerkoPair):

[email protected]@ÒD, ImageSize Ø 70D & êü Most ü [email protected]

:

,

,

,

,

>

9.3.2 Word Data ‡ WordData WordData[] (Ÿ6) Give a list of all words and phrases WordData["word"] Give a list of full word specifications representing possible uses and senses of

the given word WordData[patt, "Lookup"] Give a list of all words matching the string pattern WordData["Properties"] Give a list of all properties WordData[wordspec, "prop"] Give the value of the property for the given word specification WordData[wordspec, "prop", "form"] Give the value in the given form; possible forms: "List", "Rules", "ShortRules" WordData[All,"PartOfSpeech"] Give a list of parts of speech WordData[All,"part"] Give a list of words of a given part of speech WordData[All,"Stopwords"] Give a list of words typically ignored in text comparisons WordData contains approximately 150,000 words and phrases, and we have 37 properties: Length êü [email protected], [email protected]"Properties"D< 8149 191, 37<

Parts of speech are as follows: 8Noun, Verb, Adjective, Adverb, Preposition, Conjunction, Pronoun, Determiner, Interjection< [email protected], "PartsOfSpeech"D

Most of the words are nouns:

[email protected], "Noun"D êê Length

119 034

Let us look at what WordData knows about words or phrases beginning with matrix:

304

Mathematica Navigator

8matrix, matrix addition, matrix algebra, matrix inversion, matrix multiplication, matrix operation, matrix printer, matrix transposition< [email protected]"matrix*", "Lookup"D

Here is what WordData knows about matrix: 88matrix, Noun, Mold<, 8matrix, Noun, AnimalTissue<, 8matrix, Noun, BodySubstance<, 8matrix, Noun, Array<, 8matrix, Noun, Enclosure<, 8matrix, Noun, Stone<< [email protected]"matrix"D

The definition of the fourth meaning is as follows: 8matrix, Noun, Array< Ø HmathematicsL a rectangular array of quantities or expressions set out by rows and columns; treated as a single element and manipulated according to rules [email protected]"matrix", "Definitions"DP4T

‡ DictionaryLookup DictionaryLookup[] (Ÿ6) Give a list of all words in an English dictionary DictionaryLookup[patt] Find all words that match the string pattern patt DictionaryLookup[patt, n] Give only the first n words found DictionaryLookup[patt, IgnoreCase Ø True] Do not take the case of words into account

We consider this command in Section 16.2.1, p. 505. However, the following is an example: [email protected]"math" ~~ ___D

8math, mathematical, mathematically, mathematician, mathematicians, mathematics<

9.3.3 Color Data ‡ ColorData ColorData[] (Ÿ6) Give a list of named collections of color schemes ColorData["collection"] Give a list of color schemes in the given collection ColorData["scheme"] Give a function that generates colors in the given color scheme ColorData["scheme"][par] Give the RGB color that corresponds to the parameter value ColorData["scheme", par] Give the RGB color that corresponds to the parameter value ColorData["Properties"] Give a list of all properties ColorData["scheme", "prop"] Give the value of the property for the color scheme

We have four collections of color schemes: 8Gradients, Indexed, Named, Physical< [email protected]

Properties are as follows: 8ColorFunction, ColorList, ColorRules, Image, Name, Panel, ParameterCount, Range< [email protected]"Properties"D

Note that the color schemes can be used more easily with the ColorSchemes palette (see Section 6.2.8, p. 172).

Chapter 9 • Data

305

‡ Gradients

We have 51 gradients:

[email protected]"Gradients"D êê Short

8DarkRainbow, Rainbow, á48à, DarkBands<

Here is the color function of the rainbow color scheme: [email protected]"Rainbow"D ColorDataFunctionB80, 1<,

F

A value of this function is [email protected]"Rainbow"[email protected] [email protected], 0.72992, 0.440682D

In the next plot, we color the surface by using the rainbow color scheme to give the surface different colors according to the height of the surface: [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, ColorFunction Ø [email protected]"Rainbow"[email protected]Ò3D &L, Mesh Ø FalseD

In density plots, we do not use arguments for the color function: [email protected]@x yD, 8x, 0, p<, 8y, 0, p<, ColorFunction Ø [email protected]"TemperatureMap"DD

‡ Physical Color Schemes

We have three physical color schemes: 8BlackBodySpectrum, HypsometricTints, VisibleSpectrum< [email protected]"Physical"D

Here is the color function of the visible spectrum color scheme:

306

Mathematica Navigator

[email protected]"VisibleSpectrum"D

F

ColorDataFunctionB8380, 750<,

One of these colors is as follows: [email protected]"VisibleSpectrum"[email protected] [email protected], 0, 0.632745D

In the following plot, we use this color scheme:

[email protected], 8x, 380, 750<, 8y, 0, 100<, ColorFunction Ø [email protected]"VisibleSpectrum"D, ColorFunctionScaling Ø False, AspectRatio Ø Automatic, ImageSize Ø 180, PlotRangePadding Ø 5, FrameTicks Ø 88None, None<, 8Automatic, None<
‡ Indexed Color Schemes

We have 43 indexed color schemes:

[email protected]"Indexed"D êê Short

81, 2, 3, 4, 5, 6, 7, 8, 9, á25à, 35, 36, 37, 38, 39, 40, 41, 42, 43<

Here is the color function of the 16th indexed color scheme: [email protected] ColorDataFunctionB81, 9, 1<,

F

By clicking on a color in the following panel, we get the corresponding RGB color: [email protected], "Panel"D

The nine colors of this color scheme are as follows: [email protected], 0.0509804, 0.0235294D, á7à, [email protected], 0., 0.00784314D<

[email protected]@16, "ColorList"D, 4D

The ninth color is [email protected]@9D [email protected], 0., 0.00784314D

The following plot uses the first three colors of the color scheme:

Chapter 9 • Data

307

[email protected]@[email protected]@n xD, 8n, 3
2

3

4

5

6

-0.5 -1.0

‡ Named Color Schemes

We have five named color schemes: 8Atoms, GeologicAges, HTML, Legacy, WebSafe< [email protected]"Named"D

Here is the color function of the HTML color scheme: [email protected]"HTML"D ColorDataFunctionB8AliceBlue, á146à<,

F

By moving the mouse over the following panel, we can see the name of the color as a tooltip. By clicking on a color, we get the corresponding RGB color: [email protected]"HTML", "Panel"D

This color scheme contains 147 colors with names: [email protected]"HTML", "Range"D êê Short

88AliceBlue, AntiqueWhite, á144à, YellowGreen<<

In the following plot, we use two of these colors: [email protected]@"HTML"[email protected]"Maroon"D, [email protected], [email protected]"HTML"[email protected]"OliveDrab"D, [email protected], 0
The image of the atoms color scheme gives a special plot:

308

Mathematica Navigator

[email protected]@"Atoms", "Image"D, ImageSize Ø 380D

9.3.4 Example Data ‡ ExampleData ExampleData[] (Ÿ6) Give a list of all types of examples ExampleData["type"] Give a list of examples of the given type ExampleData[{"type", "name"}] Show the named example of the given type ExampleData[{"type", "name"}, "Properties"] Give a list of properties available for the example ExampleData[{"type", "name"}, "prop"] Give the value of the given property

Here are all the types of examples and the numbers of examples in each type:

[email protected]Ò, Length ü [email protected]ÒD< & êü [email protected], Alignment Ø 88Left, Right<
AerialImage Geometry3D LinearProgramming Matrix Sound TestAnimation TestImage Text Texture

38 27 138 2338 63 4 44 50 64

Short descriptions of the example types are as follows: Graphics and sound examples: "TestImage": test images for image processing "AerialImage": sample aerial photography images "Texture": sample textures "Geometry3D": 3D geometry data for models and shapes "TestAnimation": test animations for image processing "Sound": sample audio clips

Chapter 9 • Data

309

Mathematical examples: "Matrix": sparse and dense matrices "LinearProgramming": linear programming problems Text examples: "Text": sample text pieces ‡ TestImage, AerialImage, and Texture

Here are examples of test images, aerial images, and textures:

[email protected]@8"TestImage", "Sailboat"
:

,

,

For these examples, we can ask for the following properties: 8BitDepth, ColorSpace, Data, DataType, Graphics, GrayLevels, Image, ImageSize, Name, RGBColorArray<

[email protected]"TestImage", "Sailboat"<, "Properties"D

‡ Geometry3D, TestAnimation, and Sound

Next, we show an example of a 3D geometry. The image can be rotated with the mouse. [email protected]@8"Geometry3D", "Galleon"
8Graphics3D, GraphicsComplex, Name, PolygonCount, PolygonData, PolygonObjects, VertexData, VertexNormals<

[email protected]"Geometry3D", "Galleon"<, "Properties"D

>

310

Mathematica Navigator

The four test animation examples animate a series of photographs. These examples have two properties: 8Animation, Frames<

[email protected]"TestAnimation", "WalterCronkite"<, "Properties"D

Now we can hear a bassoon scale: [email protected]"Sound", "BassoonScale"
[email protected]"Sound", "BassoonScale"<, "Properties"D 8Channels, Data, Duration, SampledSoundList, SampleRate, Sound< ‡ Matrix

One of the more than 2000 example matrices is FIDAP007: m = [email protected]"Matrix", "FIDAP007"
[email protected]<46 570>, 81633, 1633
500

1000

1

1633 1

500

500

1000

1000

1633 1

500

1000

Matrices have the following properties:

1633 1633

Chapter 9 • Data

311

8AverageEntriesPerColumn, AverageEntriesPerRow, Bandwidth, Collection, Dimensions, Entries, Format, ID, LowerBandwidth, Matrix, MatrixStructure, Name, PatternSymmetry, PositiveDefiniteQ, Source, StrongComponents, StructuralFullRankQ, StructuralRank, Symmetry, Type, UpperBandwidth, URL<

[email protected]"Matrix", "FIDAP007"<, "Properties"D

Our matrix has, for example, the following properties:

[email protected]"Matrix", "FIDAP007"<, ÒD & êü 8"Type", "Bandwidth", "AverageEntriesPerRow", "Source"< 8Real, 277, 28.5181, ftp:êêmath.nist.govêpubêMatrixMarket2êSPARSKITêfidapêfidap007.mtx.gz<

‡ LinearProgramming

One of the smallest linear programming examples is afiro: 827, 32<

[email protected]"LinearProgramming", "afiro"<, "Dimensions"D

This example has 27 constraints and 32 variables. The form of the example is as follows: 88á32à<, [email protected]á4àD, 8á27à<, 8á32à<<

[email protected]@8"LinearProgramming", "afiro"
Thus, the example has four components. Let us give the components the names c, m, b, and n: 8c, m, b, n< = [email protected]"LinearProgramming", "afiro"
Here are the four components: 80, -0.4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.32, 0, 0, 0, -0.6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.48, 0, 0, 10.< c

[email protected]<83>, 827, 32
[email protected] êê Normal, 4D

88-1., 1., 1., 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0<, á25à, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1., 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1., 0<<

880., 80., 80., 80., b

0<, 80., 0<, 880., -1<, 80., -1<, 80., 0<, 80., 0<, 880., -1<, -1<, 80., -1<, 80., -1<, 80., 0<, 80., 0<, 8500., -1<, 80., -1<, 0<, 844., 0<, 8500., -1<, 80., -1<, 80., -1<, 80., -1<, 80., -1<, -1<, 80., -1<, 80., -1<, 80., -1<, 8310., -1<, 8300., -1<<

880, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<, 80, ¶<< n

The components correspond with the linear programming problem where the coefficient vector of the objective function is c, the constraint matrix is m, the right-hand side of the constraints is b, and the usual nonnegativity constraints apply. So, we can solve the problem as follows (for linear programming, see Section 23.2.1, p. 753): sol = [email protected], m, bD

880., 25.5, 54.5, 84.8, 18.2143, 0., 0., 0., 0., 0., 0., 0., 18.2143, 0., 19.3071, 500., 475.92, 24.08, 0., 215., 0., 0., 0., 0., 0., 0., 0., 0., 339.943, 383.943, 0., 0.<

312

Mathematica Navigator

c.sol -464.753

We could also write simply as follows: [email protected]"LinearProgramming", "afiro"
880., 25.5, 54.5, 84.8, 18.2143, 0., 0., 0., 0., 0., 0., 0., 18.2143, 0., 19.3071, 500., 475.92, 24.08, 0., 215., 0., 0., 0., 0., 0., 0., 0., 0., 339.943, 383.943, 0., 0.<

Linear programming examples have the following properties: 8Collection, ConstraintMatrix, Dimensions, Equations, LinearProgrammingData, Name, Source<

[email protected]"LinearProgramming", "afiro"<, "Properties"D

Next we ask for the explicit equations:

88obj, cons<, vars< = Exampl[email protected]"LinearProgramming", "afiro"<, "Equations"D;

For example, here are the objective function and the variables: obj -0.4 X02MPS - 0.32 X14MPS - 0.6 X23MPS - 0.48 X36MPS + 10. X39MPS 8X01MPS , X02MPS , X03MPS , X04MPS , X06MPS , X07MPS , X08MPS , X09MPS , X10MPS , X11MPS , X12MPS , X13MPS , X14MPS , X15MPS , X16MPS , X22MPS , X23MPS , X24MPS , X25MPS , X26MPS , X28MPS , X29MPS , X30MPS , X31MPS , X32MPS , X33MPS , X34MPS , X35MPS , X36MPS , X37MPS , X38MPS , X39MPS < vars

The constraints form a large expression that we do not show here. Now we can use Minimize: 8-464.753, 8X01MPS Ø 80., X02MPS Ø 25.5, X03MPS Ø 54.5, X04MPS Ø 84.8, X06MPS Ø 18.2143, X07MPS Ø 0., X08MPS Ø 0., X09MPS Ø 0., X10MPS Ø 0., X11MPS Ø 0., X12MPS Ø 0., X13MPS Ø 0., X14MPS Ø 18.2143, X15MPS Ø 0., X16MPS Ø 19.3071, X22MPS Ø 500., X23MPS Ø 475.92, X24MPS Ø 24.08, X25MPS Ø 0., X26MPS Ø 215., X28MPS Ø 0., X29MPS Ø 0., X30MPS Ø 0., X31MPS Ø 0., X32MPS Ø 0., X33MPS Ø 0., X34MPS Ø 0., X35MPS Ø 0., X36MPS Ø 339.943, X37MPS Ø 383.943, X38MPS Ø 0., X39MPS Ø 0.<< [email protected], cons<, varsD

We obtained the same solution as with LinearProgramming. ‡ Text

One of the text examples is an excerpt from Hamlet. We only show the text of the first four rows: [email protected]@8"Text", "ToBeOrNotToBe"
This is a single string, as can be seen with InputForm: % êê InputForm

"To be, or not to be,--that is the question:-- \ Whether 'tis nobler in the mind to suffer The \ slings and arrows of outrageous fortune Or to take \ arms against a sea of troubles"

For text examples, we can ask for the following properties:

Chapter 9 • Data

313

8Author, FormattedText, FullTitle, Language, Lines, NotebookExpression, String, Title, Words<

[email protected]"Text", "ToBeOrNotToBe"<, "Properties"D

The property "String" gives the same result as we presented previously. With "FormattedText" we get correct lines: [email protected]@8"Text", "ToBeOrNotToBe"<, "FormattedText"D, 173D To be, or not to be,--that is the question:-Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune Or to take arms against a sea of troubles

With InputForm we can see the newline characters \n: % êê InputForm

"To be, or not to be,--that is the \ question:--\nWhether 'tis nobler in the mind to \ suffer\nThe slings and arrows of outrageous \ fortune\nOr to take arms against a sea of \ troubles"

With "Lines" we get the text as a list of lines (each line is a string): 8To be, or not to be,--that is the question:--, Whether 'tis nobler in the mind to suffer, The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles,<

[email protected]@8"Text", "ToBeOrNotToBe"<, "Lines"D, 4D

With "Words" we get the text as a list of words (each word is a string): 8To, be,, or, not, to, be,--that, is, the, question:--, Whether, 'tis, nobler, in, the, mind, to, suffer, The, slings, and, arrows, of, outrageous, fortune, Or, to, take, arms, against, a, sea, of, troubles,<

[email protected]@8"Text", "ToBeOrNotToBe"<, "Words"D, 33D

With "NotebookExpression" we can put the text into a separate notebook (the notebook is not shown here): [email protected]@8"Text", "ToBeOrNotToBe"<, "NotebookExpression"DD NotebookObjectB

Untitled-4 F

For more about strings, see Sections 13.3.6, p. 433, and 16.2, p. 505. ‡ Additional Examples

Mathematica also has more than 100 additional example files: [email protected]$InstallationDirectory <> "êDocumentationêEnglishêSystemêExampleData"D; [email protected]@D, 1D 8100d.pdb, 1PPT.pdb, á133à, wr.rss<

These examples are mainly intended for internal use of Mathematica. The files can be imported with Import: 88Jan 03 2006, 11.82<, á249à, 8Dec 29 2006, 13.91<<

[email protected]@"ExampleDataêfinancialtimeseries.csv"D, 2D

314 This page intentionally left blank

Mathematica Navigator

10 Manipulations Introduction 315 10.1 Basic Manipulation 316 10.1.1 Introduction 316 Manipulate, ControlType, ControlPlacement 10.1.2 Sliders 318 Manipulator, Slider, VerticalSlider, Animator, Trigger, Slider2D 10.1.3 Locators 326 Locator 10.1.4 Other Controls 331 SetterBar, PopupMenu, CheckboxBar, InputField, ColorSlider, etc. 10.2 Advanced Manipulation 338 10.2.1 More about Controls 338 ControlPlacement, Delimiter 10.2.2 Handling Slow Manipulations 342 ControlActive, ContinuousAction 10.2.3 Bookmarks and More 348 SaveDefinitions, Initialization 10.2.4 Options of Manipulate 352 ControlType, Initialization, ContinuousAction, etc.

Introduction The story is told about the mathematician Littlewood that he was lecturing to a class one day and remarked about some step in a mathematical argument that it was obvious. Then he stepped back from the board and said, “Mmm, I wonder if it is obvious?” He spent about half an hour doing various calculations and finally declared with a smile, “Yes, it is obvious.” Mathematica 6 brings to us dynamic interactivity~that is, ways to create interfaces where the user can explore the output by some controls such as sliders or popup menus. Such interfaces range from interactive data viewers to interactive applications. The main command, considered in this chapter, is Manipulate. It creates an interface where an expression containing some parameters can easily be studied or animated by adjusting the parameters with some controls. We also have the lower-level command Dynamic that can be used for more special or more advanced cases or for more detailed formatting of the output. In addition, we have Animate for animations and commands such as MenuView, TabView, and OpenerView to view data in various ways. The viewers are capable of creating hierarchical views, suitable for representing large data sets. We address Dynamic, Animator, and the views in Chapter 11. The commands presented in this and the next chapter are new in Mathematica 6. Wolfram Research has a special Demonstrations Project at http:êêdemonstrations.wolfram.com to advance the use of Manipulate. Users of Mathematica 6 can submit applications of this command for publication on the website. Currently, the site contains nearly 4000 demonstrations in subject areas such as mathematics; computation; physical sciences; life sciences; business and social systems; systems, models, and methods; engineering and technology; our world; creative arts; kids and fun; and Mathematica functionality. The demonstrations and their source codes can be freely loaded.

316

Mathematica Navigator

Although interesting and useful as such, the demonstrations are also valuable in studying the use of Manipulate. The interested reader is encouraged to study the applications in the Demonstrations

Project because here we only have room for some basic examples. Regarding dynamic features, also remember palettes, hyperlinks, and slide shows that we considered in Section 3.1.3, p. 56. To avoid some printing problems, all dynamic outputs shown in this book are GIF images of the original outputs. Thus, each dynamic output was exported by Export["dyn.gif", %] and then imported by Import[%].

10.1 Basic Manipulation 10.1.1 Introduction ‡ Manipulation

Here is a simple Manipulate command and its output panel:

[email protected]@[email protected] xD, 8x, 0, 3 p<, ImageSize Ø 200D, 8a, 1, 10
We can change the value of the parameter a from 1 to 10 by moving the slider with the mouse; the plot of cosHa xL is redrawn in real time. In general, Manipulate has two arguments: the expression to be manipulated (the plotting command in the previous example) and the specifications of the parameters ({a, 1, 10}). The expression to be manipulated depends on the parameters. The output panel contains a control (e.g., a slider) for each parameter and a content area. The expression can be manipulated with the controls, and the content area shows the current state of the expression. The panel also has two special buttons: the animation button

and the utility button

. Clicking the

animation button opens animation controls and a value field showing the current value of the parameter. opens the utility menu. We discuss these buttons later. Clicking the utility button Mathematica contains several types of controls. Manipulate often automatically chooses a suitable control type based on the form of the parameter specification. The automatically chosen control can be one of the following: a manipulator, a 2D slider, a setter bar, a popup menu, a checkbox, an input field, or a color slider. We can override the automatic control by using the ControlType option. With this option we can also ask for still other control types, such as a slider, a vertical slider, an animator, a trigger, a locator, a radio button bar, a toggler, a checkbox bar, a toggler bar, or a color setter. We consider this option in the next subsection. Manipulate is an extremely powerful way to explore how various objects change as we interactively change one or more parameters.

Chapter 10 • Manipulations

317

‡ Control Types and Placements Manipulate chooses the type of control from the form of the parameter specification. With the following

option we can override the automatic setting. With this option we have access to all of the various control types. ControlType The type of control to produce in the output; possible values: Automatic, Animator, Checkbox, CheckboxBar, ColorSetter, ColorSlider, InputField, Locator, Manipulator (slider;

animator under the icon), PopupMenu, RadioButton, RadioButtonBar, Setter, SetterBar (tabs), Slider, Slider2D, Toggler, TogglerBar, Trigger (like animator), VerticalSlider, None The option can be used like other options, but a simpler way is to add the control type as an additional list element of the control specification. For example, the automatic control in the following is a slider: [email protected]@nD, 8n, 1, 200, 1
We can ask, for example, for an input field with the option:

[email protected]@nD, 8n, 1, 200, 1<, ControlType Ø InputFieldD

A simpler way is to add the control type to the parameter specification: [email protected]@nD, 8n, 1, 200, 1, InputField
The default is that the controls are placed at the top of the panel. With the following option we can adjust the placement of the controls. ControlPlacement Placement of controls in the panel; examples of values: Automatic, Left, Right, Bottom, Top [email protected]@nD, 8n, 1, 200, 1<, ControlPlacement Ø BottomD

Next, we discuss the various controls, which have been grouped as sliders, locators, and other controls.

318

Mathematica Navigator

10.1.2 Sliders ‡ Manipulator, Slider, and VerticalSlider

The following box gives the two most common forms of Manipulate. To create an interface enabling the interactive choice of the value of the parameter u with a slider and showing the corresponding value of expr: Manipulate[expr, {u, umin , umax }] (Ÿ6) u can have any value between umin and umax Manipulate[expr, {u, umin , umax , du}] u can have any value between umin and umax in steps of du

For these kinds of parameter specifications, Manipulate automatically chooses the control to be a manipulator. A manipulator means a slider together with animation controls under the button (animation is considered later). In the first case, the slider is continuous, whereas in the latter case it is discrete. As an example, we create a panel where we can show the probability density function (PDF) of the normal distribution with mean 0 and standard deviation s for any value of s in the interval @0.2, 5D. Here, we have a continuous slider. [email protected]@[email protected]@0, sD, xD, 8x, -5, 5<, PlotRange Ø 80, 2.05<, ImageSize Ø 200D, 8s, 0.2, 5
Next, we show the PDFs of c2 HnL distributions with n = 1, …, 15. Now we have a discrete slider. [email protected]@[email protected]@nD, xD, 8x, 0, 20<, PlotRange Ø 80, 0.51<, ImageSize Ø 200D, 8n, 1, 15, 1
Note that often, as in the previous examples, it is useful to define the same PlotRange for all plots. Then the plots can be more easily compared. Here are the probability functions of the Poisson distribution with parameter in the interval @0.7, 10D:

Chapter 10 • Manipulations

319

[email protected]@[email protected], [email protected]@lD, xD<, 8x, 0, 20
Note that Manipulate does its work in real time: It does not precompute all the possible outputs. Accordingly, for the manipulation to be practical, the computation caused by moving a slider should not take more than, for example, 1 second. Fortunately, nowadays quite a lot can be computed within 1 second. Manipulate[expr, {u, umin , umax , Manipulator}] Manipulate[expr, {u, umin , umax , Slider}] Manipulate[expr, {u, umin , umax , VerticalSlider}]

A manipulator can also be asked for by specifying the type of the control to be Manipulator. If we define the control to be Slider, we only get a slider without the animation controls. With VerticalSlider, we get a slider running from bottom to top (a good location for this control is on the left; use the ControlPlacement option). Here, we ask for a slider: [email protected]@nD, 8n, 1, 200, 1, Slider
‡ More Examples of Manipulate

Besides plots, we can manipulate any other expression. Below we can see any of the first 200 primes. We have used the Alignment option to place the primes at the right of the panel. [email protected]@nD, 8n, 1, 200, 1<, Alignment Ø RightD

Next, we tabulate the probabilities of getting k sixes when tossing a die n times. We can adjust the value of n.

320

Mathematica Navigator

[email protected]@[email protected], [email protected]@n, 1 ê 6.D, kD<, 8k, 0, n
3D plots can be rotated with the mouse. Another way to rotate is to use Rotate with Manipulate. To get a smooth rotation, we define a large enough PlotRange: [email protected] [email protected]@[email protected], -1, -1<, 81, 1, 1
Now we rotate a parametric surface by changing the viewpoint. To get a smooth rotation, we defined a large enough PlotRange and set SphericalRegion to be True: [email protected]@8s [email protected] [email protected], s [email protected] [email protected], -s [email protected]<, 8s, 0, 2 p<, 8t, 0, p<, ViewPoint Ø [email protected], [email protected], 1<, Boxed Ø False, Axes Ø False, PlotRange Ø 88-8, 8<, 8-8, 8<, All<, SphericalRegion Ø True, PlotPoints Ø 20, ImageSize Ø 200D, 8q, 0, p
Next, we show how a small sphere moves around a larger sphere:

Chapter 10 • Manipulations

321

[email protected]@[email protected], [email protected] [email protected], [email protected], 0<, 0.2D<, Boxed Ø False, ViewPoint Ø 81.3, -2.4, 0.8<, PlotRange Ø 88-2, 2<, 8-2, 2<, 8-1, 1<<, ImageSize Ø 200D, 8t, 0, 2 p
‡ Animation

We have several ways to run an animation: Animate[expr, {u, umin , umax }] Manipulate[expr, {u, umin , umax }] Click Manipulate[expr, {u, umin , umax }] Click

and use the animation controls and choose Autorun

Manipulate[expr, {u, umin , umax , Animator}] Manipulate[expr, {u, umin , umax , Trigger} ] Animate is considered in Section 11.1.2, p. 365. Here is an example:

[email protected][email protected]@n, xD, 8x, -1, 1<, PlotRange Ø 1.05, ImageSize Ø 130D, 8n, 0, 10, 1<, AnimationRunning Ø FalseD

We can run the animation by clicking the play button. We can also drag the slider with the mouse to show a particular plot. Manipulate produces very much the same view: [email protected] [email protected]@n, xD, 8x, -1, 1<, PlotRange Ø 1.05, ImageSize Ø 200D, 8n, 0, 10, 1
322

Mathematica Navigator

Here, we can drag the slider. However, by clicking the animation button next to the slider, we also get controls to play an animation and a field showing the current value of the parameter: [email protected] [email protected]@n, xD, 8x, -1, 1<, PlotRange Ø 1.05, ImageSize Ø 200D, 8n, 0, 10, 1
Clicking the utility

button, we get a menu, with one of its items being Autorun. If we choose this

item, an animation is run automatically (for each parameter in turn, if we have several parameters). The animation can be stopped by clicking close. [email protected] [email protected]@n, xD, 8x, -1, 1<, PlotRange Ø 1.05, ImageSize Ø 200D, 8n, 0, 10, 1
A fourth way to get an animation is to ask Manipulate to produce an animator:

[email protected]@[email protected], xD, 8x, -1, 1<, PlotRange Ø 1.05, ImageSize Ø 200D, 8n, 0, 1 μ 0, 1, Animator
A fifth way is to ask for a trigger. It is like an animator but does not have a slider:

Chapter 10 • Manipulations

323

[email protected]@[email protected], xD, 8x, -1, 1<, PlotRange Ø 1.05, ImageSize Ø 160D, 8n, 0, 10, 1, Trigger
In summary, Animate is intended to automatically show a series of plots from the beginning to the end (although we can also drag the slider by ourselves). Manipulate produces an interface where we can adjust the parameter in question by ourselves (although we can also run an animation). If we only have one parameter, there is not much difference between Animate and Manipulate. ‡ Initial Values, Labels, and Current Values Manipulate[expr, {{u, uinit }, umin , umax }] The initial value of u is uinit Manipulate[expr, {{u, uinit , ulbl }, umin , umax }] The initial value of u is uinit and the label of the

slider is ulbl Manipulate[expr, {u, umin , umax , Appearance Ø "Labeled"}] Show the current value of u

Previously, we created a panel showing the plot of some Chebyshev polynomials. The starting value 1 of the parameter n produced a somewhat noninteresting plot of a constant. It would be good if the panel, immediately after executing the Manipulate command, would show something more interesting. This can be done by giving an initial value for the parameter: [email protected]@[email protected], xD, 8x, -1, 1<, PlotRange Ø 1.05, ImageSize Ø 200D, 88n, 5<, 0, 10, 1
The label on the left-hand side of the slider is, by default, the corresponding parameter. We can give another label. As an example, next we write the parameter of the exponential distribution as 1 ê l. Then the expected value of the corresponding random variable is l. Hence, we can label the slider as EHXL:

324

Mathematica Navigator

[email protected]@[email protected]@1 ê lD, xD, 8x, 0, 3<, PlotRange Ø 80, 5.1<, ImageSize Ø 200D, 88l, 0.25, "E HX L"<, 0.2, 10
By clicking the animation button , we can see the current value of the parameter; this is shown in the previous panel. Another way to see this value is to use the Appearance option. The value of the parameter can be seen next to the icon: [email protected]@[email protected]@1 ê lD, xD, 8x, 0, 3<, PlotRange Ø 80, 5.1<, ImageSize Ø 200D, 88l, 0.25, "E HX L"<, 0.2, 10, Appearance Ø "Labeled"
‡ Two Manipulators and Slider2D

If we have two parameters, we can ask either for two usual 1D sliders or for one 2D slider: Manipulate[expr, {x, xmin , xmax }, {y, ymin , ymax }] Control the two parameters with two sliders Manipulate[expr, {u, {xmin , ymin }, {xmax , ymax }}] Control the two parameters with a 2D slider

A 2D slider can also be asked for by specifying the type of the control to be Slider2D. With a manipulation, we can investigate the PDF of a beta distribution with respect to its two parameters. Here, we use the LabelStyle option to make the labels a and b bold and somewhat larger.

Chapter 10 • Manipulations

325

[email protected]@[email protected]@a, bD, xD, 8x, 0, 1<, PlotRange Ø 80, 4.1<, ImageSize Ø 200D, 88a, 2.5<, 0.01, 3, Appearance Ø "Labeled"<, 88b, 1.5<, 0.01, 3, Appearance Ø "Labeled"<, LabelStyle Ø 8Bold, 12
We can also ask for a 2D slider that allows simultaneous changes of the parameters. In the next example, the 2D slider can be moved on the region H0.01, 3L μ H0.01, 3L. With the ControlPlacement option, we asked to put the 2D slider at the left of the panel. [email protected]@[email protected]@aP1T, aP2TD, xD, 8x, 0, 1<, PlotRange Ø 80, 4.1<, ImageSize Ø 200D, 88a, 82.5, 1.5<<, 80.01, 0.01<, 83, 3<<, ControlPlacement Ø LeftD

In the 2D slider, the values of a go from left bottom to right bottom, and the values of b go from bottom left to top left. For example, by moving the slider from bottom left to top right we see that for these values of the parameters the PDF is symmetric, one of the PDF’s being the one of the uniform distribution. ‡ Several Manipulators

We can have an arbitrary amount of parameters. In the following example, we ask for three sliders. The plot describes the evolution of the solution of a logistic differential equation. We can adjust the initial value and the two parameters of the model.

326

Mathematica Navigator

[email protected]@M ê H1 + HM ê y0 - 1L [email protected] M tDL, 8t, 0, 20<, PlotRange Ø 80, All<, ImagePadding Ø 8815, 2<, 815, 5<<, ImageSize Ø 200D, 88y0, 0.2, "yH0L"<, 0.001, 5, Appearance Ø "Labeled"<, 88r, 0.15, "r "<, 0, 2, Appearance Ø "Labeled"<, 88M, 4, "M "<, 0, 10, Appearance Ø "Labeled"
Note that in this example, we used the ImagePadding option to make suitable space around the plot so that even if the y tick labels change, the axes of the plot do not move.

10.1.3 Locators ‡ Locator

In the following example, we create a point that we can move with a 2D slider: [email protected]@[email protected], [email protected]<, Frame Ø True, FrameTicks Ø None, PlotRange Ø 1.2, ImageSize Ø 60D, 88p, 80, 0<<, 8-1, -1<, 81, 1<<, ControlPlacement Ø LeftD

However, we have a special control, called a locator, that is specifically designed for points that can be moved. Manipulate[expr, {pt, Locator}] Create an interface enabling the interactive movement of a Manipulate[expr, {{pt, {x1, y1}}, Locator}] The initial position of the locator is Ix1 , y1 M

point pt (displayed as a locator) and showing the corresponding value of expr

We do not get a locator automatically; we have to define the control type as a Locator. Here is a simple example:

Chapter 10 • Manipulations

327

[email protected]@8<, PlotLabel Ø [email protected] êê Chop, 83, 2
We created an empty graphics, containing only a frame and a plot label. However, the plot also contains a locator that can be moved within the frame. The position of the locator is shown in the plot label. For a locator, we do not need to define ranges because a locator takes suitable ranges from the ranges of the plot. Now we create three locators: [email protected]@8Orange, [email protected], p2, p3
By dragging on any one of the locators, the plot changes accordingly. You can also click anywhere in the plot and the nearest locator moves to that point. ‡ More about Locator

It is almost always useful to define initial values for the locators. If we have several locators, we can treat them as a whole, as is shown in the second item here: {{pt, {x1, y1}}, Locator} Represent pt as a locator whose initial position is Ix1 , y1 M

positions are Ix1 , y1 M, …, Ixn , yn M

{{pt, {{x1, y1}, … , {xn, yn}}}, Locator} Represent pt as a set of locators whose initial

We can now write the preceding example as follows:

328

Mathematica Navigator

[email protected]@8Orange, [email protected]<, PlotRange Ø 1.1, ImageSize Ø 120D, 88p, 88-0.9, -0.9<, 80.9, -0.9<, 80, 0.9<<<, Locator
With the Appearance option we can define other symbols for the locators. {{pt, {x1, y1}}, Locator, Appearance Ø obj} Use obj as a locator object; examples of values of obj: Automatic (the default “crosshairs” appearance), None (display nothing visible), "*", "Ê", Graphics[{PointSize[Large], Point[{0, 0}]}]

Now, we show 50 random locators as colored points (the symbol Ë can be typed as \[FilledSmallCircle]). Each point can be moved separately. [email protected]@8<, PlotRange Ø 1.1, ImageSize Ø 150D, 88pt, [email protected], 1<, 850, 2
‡ Adding and Removing Locators

The number of locators need not be fixed. With an option, we can allow more locators to be created or old locators to be removed. {{pt, {x1, y1}}, Locator, LocatorAutoCreate Ø True} Allow autocreation and autodeletion of

locators Now, if you hold down the ‡ key (Windows) or Ì key (Macintosh) and then click on the plot, a new locator is created. If you hold down the ‡ or Ì key and then click on an existing locator, that locator is removed. Consider again the familiar triangle and try adding and removing locators:

Chapter 10 • Manipulations

329

[email protected]@8Orange, [email protected]<, PlotRange Ø 1, ImageSize Ø 120D, 88p, 88-0.9, -0.9<, 80.9, -0.9<, 80, 0.9<<<, Locator, LocatorAutoCreate Ø True
‡ Example: Interactive Interpolation and Curve Fitting

The document tutorialêIntroductionToManipulate in the Documentation Center contains interesting examples of interactive interpolating and curve fitting. First, we consider interpolation: [email protected]@[email protected], xD, 8x, -2, 2<, PlotRange Ø 10.5, ImageSize Ø 230D, 88points, [email protected], 2<, 82, 2
Here, the points to be interpolated are represented as locators. The figure shows the interpolating polynomial. Points can be added and removed by ‡- or Ì-clicking. Now, move the locators and add new locators to see how the interpolating polynomial changes. For more about interpolating polynomials, see Section 24.1.1, p. 792. Similarly, we can interactively investigate polynomial curve fitting: [email protected]@8x, fi<, fi = [email protected], x ^ [email protected], orderD, xD; [email protected], 8x, -2, 2<, PlotRange Ø 5.1, ImageSize Ø 230DD, 88order, 1<, 1, 10, 1, Appearance Ø "Labeled"<, 88points, [email protected], 2<, 83, 2
330

Mathematica Navigator

Again, the points to be fitted are represented as locators. The figure shows the fitted polynomial. Points can be added and removed by ‡- or Ì-clicking. Now, move the locators, add new locators, and change the order of the polynomial to see how the fit changes. Note that in the previous command we used DynamicModule to make the x variable local; now the command works even if x happens to have a value. DynamicModule is considered in Section 11.2.1, p. 371. It suffices here to say that it is used like Module and is designed for dynamic calculations. For more on curve fitting, see Section 25.1.1, p. 812. ‡ Example: Interactive Differential Equation Plotting

Next, we study a differential equation model of competing species. In the initial position of the panel, we show four trajectories of the solution of the equations, corresponding to four starting points. The four points are represented by locators so that you can move them with the mouse. You can also create new trajectories and delete old ones. This model is also studied in Section 26.3.2, p. 855. [email protected]@8x, y, t, sol<, sol = [email protected], [email protected]< ê. [email protected] '@tD == [email protected] H2 - 2 ê 3 [email protected] - 2 [email protected], y '@tD == [email protected] H2 - 4 ê 3 [email protected] - [email protected], [email protected] == ÒP1T, [email protected] == ÒP2T<, [email protected], [email protected]<, 8t, 0, 10
The examples of interactive interpolation, fitting, and differential equation plotting begin to give an impression of the power of Manipulate. In a few lines of easy code we can create impressive interactive applications. ‡ Geometric Constraints on Points

In the next examples, we create points that are constrained on a curve. The points can be moved with locators. In the first example, we can freely move a locator, but it in turn moves an arrow whose head is on a circle:

Chapter 10 • Manipulations

331

[email protected]@[email protected], [email protected], [email protected], 0<, [email protected]
Here, the pt is a locator. The position of the arrowhead is obtained from the locator position by normalizing the latter (i.e., by dividing with the norm). Thus, the arrowhead always has norm 1, and this means that the point is on a circle. Now, we create a locator that moves a point on a curve. With the Appearance option, we have asked not to show the locator: [email protected]@[email protected], 8x, 0, 10<, Epilog Ø [email protected], [email protected]@ptD, [email protected]@ptDD
10.1.4 Other Controls ‡ SetterBar and RadioButtonBar Manipulate[expr, {u, {u1 , u2 , … }}] Create an interface enabling the interactive choice of the

value of the parameter u from the values u1 , u2 , … with a setter bar or popup menu and showing the corresponding value of expr For this type of parameter specification, we automatically get either a setter bar or a popup menu. Indeed, if we have at most five values for u, we get a setter bar (a row of tabs); for at least six values we get a popup menu. A setter bar or popup menu can also be asked for by specifying the control type to be SetterBar (or Setter) or PopupMenu. The type RadioButtonBar (or RadioButton) produces a set of radio buttons.

332

Mathematica Navigator

Manipulate[expr, {u, {u1 , u2 , … }, SetterBar}] Manipulate[expr, {u, {u1 , u2 , … }, PopupMenu}] Manipulate[expr, {u, {u1 , u2 , … }, RadioButtonBar}]

Setter bars and popup menus are useful in situations in which we are interested in an irregular set of values of the parameter that cannot be represented with a regular iteration specification. We can then define the list of values in which we are interested. In the following example, we can ask for some quantiles of the standard normal distribution: [email protected]@[email protected], 1D, qD, 8q, 80.9, 0.95, 0.99, 0.999<
We got a setter bar or a set of tabs. A TabView, considered in Section 11.1.1, p. 360, produces a very similar view:

[email protected]Ò Ø [email protected]@0, 1D, ÒD & êü 80.9, 0.95, 0.99, 0.999
We can also use radio buttons: [email protected]@[email protected], 1D, qD, 8q, 80.9, 0.95, 0.99, 0.999<, RadioButtonBar
‡ PopupMenu

We continue the preceding examples. In the next example, we have more than five items so that now we get a popup menu: [email protected]@[email protected], 1D, qD, 8q, 80.8, 0.85, 0.9, 0.95, 0.99, 0.999<
A MenuView, considered in Section 11.1.1, p. 358, produces a very similar view:

Chapter 10 • Manipulations

333

[email protected] Ò Ø [email protected]@0, 1D, ÒD & êü 80.8, 0.85, 0.9, 0.95, 0.99, 0.999
Now we ask for the plots of the basic trigonometric functions:

[email protected]@[email protected], 8x, -p, p<, PlotRange Ø 8-5.1, 5.1
‡ Checkbox and Toggler

A special case of the control specification {u, {u1 , u2 , … }} presented for setter bars is the one in which the possible values are True or False: Manipulate[expr, {u, {True, False}}] u takes on the values True and False

For this kind of parameter specification, Manipulate automatically chooses the control to be a checkbox. A checkbox can also be asked for by specifying the control type to be Checkbox. In the next example, we get the plot of the probability density function of various Poisson distributions. In addition, we can ask, with a checkbox, to also plot the cumulative distribution function. [email protected] = [email protected]; [email protected] [email protected], [email protected]@88x, [email protected], xD<, 8x, [email protected], xD<<, 8x, 0, 15
334

Mathematica Navigator

Manipulate[expr, {u, {u1 , u2 , … }, Checkbox}] Manipulate[expr, {u, {u1 , u2 , … }, Toggler}]

If we have more than two choices, clicking the checkbox goes through the alternatives: [email protected]@[email protected], 1D, qD, 8q, 8.9, .95, .99, .999<, Checkbox
In the next output, we have a toggler. When clicking the number next to q, the number goes through the given alternatives:

[email protected]@[email protected], 1D, qD, 8q, 8.9, .95, .99, .999<, Toggler
‡ CheckboxBar and TogglerBar Manipulate[expr, {u, {u1 , u2 , … }, CheckboxBar}] Manipulate[expr, {u, {u1 , u2 , … }, TogglerBar}]

With checkbox bars and toggler bars we can choose a list of values from a given list (the Initialization option is explained in Section 10.2.3, p. 349): [email protected]@[email protected], 1D, qD, 8q, 8.9, .95, .99, .999<, CheckboxBar<, Initialization ß Hq = 8
[email protected]@[email protected], 1D, qD, 8q, 8.9, .95, .99, .999<, TogglerBar<, Initialization ß Hq = 8
Chapter 10 • Manipulations

335

‡ InputField

To create an interface enabling the interactive choice of the value of the parameter u with an input field and showing the corresponding value of expr: Manipulate[expr, {u}] The input field is initially empty Manipulate[expr, {u, u0 }] The input field initially contains u0 For these kinds of parameter specifications, Manipulate automatically chooses the control to be an input field. An input field can also be asked for by specifying the control type to be InputField. Here is an example: [email protected]@f, 8x, a, b<, ImageSize Ø 130D, 8f, [email protected]<, 8a, 0<, 8b, 2 p
We got three input fields~one each for the function and the starting and ending points. After executing the Manipulate command, the input fields contain the values of parameters we gave in the command. These values should be chosen to be typical: With the aid of the example, the user of the panel should be able to produce similar outputs. Indeed, we can now write new functions to be plotted and new starting and ending points; press Í to go from one field to the next. Once the new inputs are ready, press the Á key to get the new plot. As another example, we create an interface where we can ask for binomial probabilities:

336

Mathematica Navigator

[email protected] [email protected]@88"P HX = kL:", [email protected]@n, pD, kD<, 8"P HX § kL:", [email protected]@n, pD, kD<<, Spacings Ø 2D, [email protected]@8x, [email protected]@n, pD, xD<, 8x, 0, n
Once you have set the parameters n, p, and k, press the Á key. In Section 11.2.3, p. 384, we create a similar panel by using Dynamic. ‡ ColorSlider and ColorSetter Manipulate[expr, {u, col}] Create an interface enabling, with a color slider, the interactive choice

of a color as the value of the parameter u and showing the corresponding value of expr; the initial value of the color is col For this kind of parameter specification, Manipulate automatically chooses the control to be a color slider. A color slider can also be asked for by specifying the control type to be ColorSlider. The color can be selected by clicking on the slider. We can also ask for a ColorSetter. When we click on a color setter, a separate window appears where we can choose the color. Here we have both a color slider and a color setter: [email protected]@8col, [email protected]<, ImageSize Ø 30D, 8col, Red
:

,

>

Chapter 10 • Manipulations

337

Thus far, we have manipulated plots produced by commands such as Plot or ListPlot. Interesting manipulations can also be done with Graphics. Here is a simple example: [email protected]@8col1, [email protected], [email protected], col2, [email protected], rD<, Frame Ø True, FrameTicks Ø None, PlotRange Ø 2.05, ImageSize Ø 130D, 88p, 80, 0<, "Center point"<, 8-1, -1<, 81, 1<<, 88r, 0.8, "Radius"<, 0, 1<, 88col1, Blue, "Point color"<, Blue<, 88col2, Red, "Circle color"<, Red<, Alignment Ø Center, ControlPlacement Ø LeftD

Note that in manipulating graphics, it is almost always useful to give a fixed PlotRange. Previously, we gave the value 2.05 for this option; it means that the plot range is H-2.05, 2.05L in both the x and the y direction. Without a fixed plot range, the plot range varies according to the plotted figure and we cannot get a good idea of the relative sizes and positions of the manipulated plots. As another example of using colors, next we create an interface that enables us to study how RGB colors change when we adjust the amount of red, green, and blue: [email protected]@[email protected], green, blueD, [email protected]<, ImageSize Ø 60D, 88red, 0.75, [email protected], [email protected]<, ImageSize Ø 20D<, 0, 1, Appearance Ø "Labeled"<, 88green, 0.5, [email protected], [email protected]<, ImageSize Ø 20D<, 0, 1, Appearance Ø "Labeled"<, 88blue, 0.25, [email protected], [email protected]<, ImageSize Ø 20D<, 0, 1, Appearance Ø "Labeled"<, ControlPlacement Ø LeftD

338

Mathematica Navigator

10.2 Advanced Manipulation 10.2.1 More about Controls ‡ Slowing Down the Speed of a Slider

Consider again the plots of the PDF of the beta distribution:

[email protected]@[email protected]@a, bD, xD, 8x, 0, 1<, PlotRange Ø 80, 4.1<, ImageSize Ø 200D, 88a, 2.5<, 0.01, 3, Appearance Ø "Labeled"<, 88b, 1.0<, 0.01, 3, Appearance Ø "Labeled"
If you let the slider of a be in the default position and slightly move the slider of b, the plot changes so rapidly that we lose the smooth deformation of the curve; we get a series of separate plots that differ clearly from each other. Fortunately, we can fine-tune the speed of the slider. Hold down the ‡ key on a Windows machine or the ı key on a Macintosh machine, and then move the slider. Now the action of the slider is slowed down by a factor of 20 relative to the movements of the mouse. With this method, we can see in our example more clearly what happens near the value b = 1. While pressing the special keys, we can also move the mouse pointer outside the slider; then the value of the parameter keeps changing. The speed of the slider can still be slowed down. In addition to the ‡ or ı key, if we also hold down the ‚ key, the speed is slowed down by an additional factor of 20. By holding down ‡, ‚, and ˜ keys, the speed is still slowed down by a factor of 20. These techniques apply, besides for sliders, for 2D sliders and locators. ‡ Enhancing the Controls

We can fine-tune the controls by defining their placement and style and by adding dividers and text among the controls. Often the best place for the controls is at the top of the panel. However, we can also ask to put the controls at the left, bottom, or right by using the ControlPlacement option. ControlPlacement Placement of controls; examples of values: Automatic, Left, Right, Bottom, Top

A single value such as Left defines that all controls are at the left. The placement of the controls can also be defined differently for the variables. Indeed, we can either define the value of ControlPlacement to be a list of placements or define the placement for each parameter separately. We do the latter in the next example:

Chapter 10 • Manipulations

339

[email protected]@[email protected], [email protected]@n, W, TD, xD<, 8x, [email protected], W + n - TD, [email protected], WD
The controls can be grouped by using Delimiter among the parameter specifications. A delimiter is shown by a line between the controls: [email protected]@[email protected], [email protected]@n, W, TD, xD<, 8x, [email protected], W + n - TD, [email protected], WD
We can also add text among the controls. The texts can be pure strings or styled with Style:

340

Mathematica Navigator

[email protected]@[email protected]@nD, xD, 8x, 0, 20<, PlotRange Ø 80, 0.51<, ImageSize Ø 200D, [email protected]"Degrees of Freedom", Bold, 10D, 88n, 4<, 1, 15, 1
Using Item, we can define different alignments: [email protected]@[email protected]@nD, xD, 8x, 0, 20<, PlotRange Ø 80, 0.51<, ImageSize Ø 200D, [email protected]@"Degrees of Freedom", BoldD, Alignment Ø CenterD, 88n, 4<, 1, 15, 1
‡ Interdependent Controls

In the next example, we again plot the PDF of a hypergeometric distribution. The distribution arises when we draw, without replacement, n balls from an urn containing a total of T balls, of which W are white. A random variable with this distribution gives the number of white balls in the sample.

Chapter 10 • Manipulations

341

[email protected]@[email protected], [email protected]@n, W, TD, xD<, 8x, [email protected], W + n - TD, [email protected], WD
Here, first let T, the total number of balls, be at its maximum. Then try adjusting the value of n, the sample size. Then, leave n somewhere in the middle and try adjusting the value of W, the number of white balls. Then, leave W somewhere in the middle and try adjusting the value of T. Try again giving T increasingly smaller values. You observe that the sliders of W and n also change, in the opposite direction! Click on the buttons next to the right of the sliders of W and n. Now you can see the actual values of these parameters. As you now move the slider of T, you see that the value of W or n does not change. Note that the upper limits of W and n are T. Thus, the smaller is T, the smaller are the upper limits of W and n so that fixed values of W or n are increasingly nearer the upper limit. This causes the movement of the sliders of W and n. When you move the slider of T to the left, at some point one of the sliders of W and n reaches its right end; let it be the slider of W. If you continue moving the slider of T to the left, a red background appears for the slider of W. Also, the figure disappears and we only get the code of the plot with a pink background and we get an error message above the plot. This means that something is wrong with this parameter. Indeed, in our example, the cause is that we cannot have more white balls in the urn than we have total balls. The list of values to be plotted became empty. If you still continue moving the slider of T to the left, at some point another slider also gets a red background. We can add the conditions that if T becomes smaller than W, then W should be replaced by T, and if T becomes smaller than n, then n should be replaced by T:

342

Mathematica Navigator

[email protected]@T < W, W = TD; [email protected] > T, n = TD; [email protected]@8x, [email protected]@n, W, TD, xD<, 8x, [email protected], W + n - TD, [email protected], WD
Now the pink background only flashes and the values of W and n are automatically made smaller if we make T small enough. ‡ Using Gamepads and Joysticks

Usually, the controls of a panel created by Manipulate are used with the mouse. However, there are other input devices such as gamepads and joysticks. Devices that enable us to use the controls are called controllers. Indeed, gamepads and joysticks can also be used to interact with the outputs of Manipulate. These devices have the advantage that they have several buttons and joysticks so that we can use several controls at the same time. To use a gamepad or joystick, simply plug it in and select (highlight) with the mouse the cell bracket containing the Manipulate output you want to control. Mathematica automatically detects a gamepad or joystick, and Manipulate automatically links as many parameters as possible with the available joysticks and buttons. We do not go into further detail; see the document tutorialêIntroductionToManipulate in the Documentation Center.

10.2.2 Handling Slow Manipulations ‡ Manipulating 3D Graphics

We can also manipulate 3D graphics:

Chapter 10 • Manipulations

343

[email protected]@2 [email protected] [email protected], [email protected] [email protected], [email protected]<, 8u, p, a<, 8v, -p, p<, ImageSize Ø 150, PlotRange Ø 2D, 88a, 1<, 0, p - 0.01
When you try the slider of this panel, you will see that when you drag the slider, the quality of the plot is not as high as usual. As soon as you release the mouse button, a high-quality plot is rendered. This behavior is designed to speed up the manipulation. Indeed, a 3D plot requires a lot of computation; if all the plots during manipulation were of high quality, the manipulation would often be too slow. Manipulated 3D plots can also be rotated with the mouse. ‡ Showing Degraded Output during Manipulation

When we previously considered the manipulation of 3D plots, we noted that the quality of the plot is automatically downgraded when moving a slider to make the manipulation speedier. Similarly, we can do this in any manipulation: With the ControlActive command, we can ask for simpler and faster computations while a slider is moved and produce a quality output when the mouse is released. ControlActive[act, norm] (Ÿ6) Evaluates to act if a control is actively being used, and to norm

otherwise In plotting, a useful way to speed up the manipulation is to use fewer plot points when moving the mouse and use more points to produce the plot when the mouse is released: [email protected]@[email protected]@nD x yD, 8x, 0, p<, 8y, 0, p<, ImageSize Ø 150, PlotPoints Ø [email protected], 50DD, 8n, 1, 5
344

Mathematica Navigator

Here, we used 10 as the value of PlotPoints when the slider is moved and the value 50 to produce the final plot. In fact, this kind of functionality is the default in density plots, although the final plot is produced with a smaller amount of points. The default functionality corresponds with the following use of the PerformanceGoal option: [email protected]@[email protected]@nD x yD, 8x, 0, p<, 8y, 0, p<, ImageSize Ø 150, PerformanceGoal Ø [email protected]"Speed", "Quality"DD, 8n, 1, 5
The ControlActive command can also be used to control the value of the MaxRecursion option. This option defines the maximum number of recursive subdivisions allowed in improving the quality of a plot. An application of ControlActive to MaxRecursion can be seen in a manipulation in Section 26.4.3, p. 876. ‡ Showing Only the Final Output of Manipulation

Another solution to slow manipulations is to arrange so that during movement of the slider the output is not updated. Only when we release the mouse is the output updated. ContinuousAction Whether to update the panel continuously when controls are changed; possible

values: Automatic, True, False (updating only when mouse is released) Usually, the output is continuously updated. If we ask not to update continuously, then we can rapidly move the slider. Here is an example: [email protected]@2 [email protected] [email protected], [email protected] [email protected], [email protected]<, 8u, p, a<, 8v, -p, p<, ImageSize Ø 100, PlotRange -> 2D, 8a, 0, p - 0.01<, ContinuousAction Ø FalseD

Usually, if an update takes more than 5 seconds, the calculation is aborted. With the previous option, there is no 5-second limit.

Chapter 10 • Manipulations

345

‡ Example: Two-Dimensional Normal Distribution

The following panel shows the contour plot of the probability density function of the 2D normal distribution with means m1 and m2 , standard deviations s1 and s2 , and correlation r. The panel also shows the corresponding marginal distributions. To speed up the computations, we have asked for only five contours. If the manipulation seems to be too slow, you can add the option ContinuousAction Ø False. << MultivariateStatistics` [email protected] [email protected]@[email protected]@m2, s2D, yD, 8y, -6, 6<, PlotRange Ø All, ImageSize Ø 150D, [email protected]@ [email protected], m2<, 88s1 ^ 2, r s1 s2<, 8r s1 s2, s2 ^ 2<
We can also put the marginal densities in the control area. This requires the plotting commands for the marginals to be enclosed by Dynamic so that the plots are dynamically updated; Dynamic is considered in Section 11.2, p. 369.

346

Mathematica Navigator

<< MultivariateStatistics` [email protected]@ [email protected]@8m1, m2<, 88s1 ^ 2, r s1 s2<, 8r s1 s2, s2 ^ 2<
‡ Updating the Output Only Partly

Each time we manipulate an expression, the entire first argument of Manipulate is evaluated anew to reflect the new values of the parameters. This is suitable in most cases. However, there are situations in which we would like only some parts of the first expression to be evaluated anew. One situation is when we specifically want only some aspects of the output to be updated, to be able to see the effect of only some parameters. Another is when it would be advantageous not to evaluate the entire first argument to reduce computing time. In the following example, we generate a sample of 10,000 random numbers from the standard normal distribution and show a histogram. We use the SaveDefinitions option (see Section 10.2.3, p. 348).

Chapter 10 • Manipulations

347

<< Histograms` [email protected]@8r<, r = [email protected]@0, 1D, 10 000D; [email protected], HistogramCategories Ø n, ApproximateIntervals Ø False, ImageSize Ø 200, HistogramRange Ø 8-5, 5<, Ticks Ø [email protected], 4D, Automatic
The adjustable parameter n gives the number of histogram categories. The panel works but has a drawback: Each time we adjust n, the first argument of Manipulate is evaluated anew, causing a new sample to be drawn from the normal distribution. We would instead like to see the same sample displayed with various values of n. To solve the problem, calculate the sample outside of Manipulate: [email protected] = [email protected]@0, 1D, 10 ^ 5D<, [email protected]@s, HistogramCategories Ø n, ApproximateIntervals Ø False, ImageSize Ø 200, HistogramRange Ø 8-5, 5<, Ticks Ø [email protected], 4D, Automatic
When we now adjust n, the sample will remain the same. To investigate a different sample, execute the command again. Another solution is to enclose the command that calculates the histogram with Dynamic:

348

Mathematica Navigator

[email protected]@8t<, t = [email protected]@0, 1D, 10 ^ 5D; [email protected]@t, HistogramCategories Ø n, ApproximateIntervals Ø False, ImageSize Ø 200, HistogramRange Ø 8-5, 5<, Ticks Ø [email protected], 4D, Automatic
Again, when we now adjust n, the sample will remain the same. To investigate a different sample, execute the command anew. The use of Dynami