15.9 Create graphics with Asymptote
Asymptote (https://asymptote.sourceforge.io) is a powerful language for vector graphics. You may write and run Asymptote code in R Markdown with the asy
engine if you have installed Asymptote (see its website for instructions on the installation). Below is an example copied from the repository https://github.com/vectorgraphics/asymptote, and its output is shown in Figure ??:
import graph3;
import grid3;
import palette;
.prc = false;
settings
=orthographic(0.8,1,2);
currentprojection(500,400,IgnoreAspect);
size
(pair z) {return cos(2*pi*z.x)*sin(2*pi*z.y);}
real f
=surface(f,(-1/2,-1/2),(1/2,1/2),50,Spline);
surface s
=planeproject(unitsquare3)*s;
surface S.colors(palette(s.map(zpart),Rainbow()));
S(S,nolight);
draw(s,lightgray+opacity(0.7));
draw
(XYZgrid); grid3
Note that for PDF output, you may need some additional LaTeX packages, otherwise you may get an error that looks like this:
! LaTeX Error: File `ocgbase.sty' not found.
If such an error occurs, please see Section 1.3 for how to install the missing LaTeX packages.
In the asy
chunk above, we used the setting settings.prc = false
. Without this setting, Asymptote generates an interactive 3D graph when the output format is PDF. However, the interactive graph can only be viewed in Acrobat Reader. If you use Acrobat Reader, you can interact with the graph. For example, you can rotate the 3D surface in Figure ?? with your mouse.
15.9.1 Generate data in R and read it in Asymptote
Now we show an example in which we first save data generated in R to a CSV file (below is an R code chunk):
<- seq(0, 5, l = 100)
x <- sin(x)
y writeLines(paste(x, y, sep = ","), "sine.csv")
Then read it in Asymptote, and draw a graph based on the data as shown in Figure ?? (below is an asy
code chunk):
import graph;
(400,300,IgnoreAspect);
size.prc = false;
settings
// import data from csv file
=input("sine.csv").line().csv();
file in[][] a=in.dimension(0,0);
real=transpose(a);
a
// generate a path
= graph(a[0],a[1]);
path rpath = (1,0)--(5,1);
path lpath
// find intersection
=intersectionpoint(rpath,lpath);
pair pA
// draw all
(rpath,red);
draw(lpath,dashed + blue);
draw("$\delta$",pA,NE);
dot("$x$",BottomTop,LeftTicks);
xaxis("$y$",LeftRight,RightTicks); yaxis