Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

r - Plot inside a plot

I have the plot 1

curve(exp(x), from=1, to=5, lwd=5)
curve(150-exp(x), from=1, to=5, lwd=5, col="darkblue",add=T)

and inside it i would like to add the following plot 2

par(mar=c(7,7,1,1))
curve(exp(x), from=1, to=5, lwd=7, xlab="chi", ylab="exp(x)", cex.lab=4,axes=F)
axis(1, labels=NA,at=c(0,5))
axis(2, labels=NA,at=c(0,150))
text(1,120,"Alpha",adj=c(0,0),cex=3)
text(3.5,10,"Beta",adj=c(0,0),cex=3)

In order to obtain the following

Combined

I would also like to make plot 2 transparent so that if there are some elements of plot 1 behind plot 2 they will still show (just like the blue line). Also important are the bigger labels of plot 2 and the absence of labels and ticks in it's axes.

Is this possible? Please only base R solutions (no ggplot2 / no lattice)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK, here's an example, which I plotted to a 10 by 10 inch pdf. (Part of what's frustrating about using par(fig = ) et al. is that their effects are very much dependent on the size of the plotting device.)


Edited to add some explanation:

The base graphic plotting parameter par("fig") describes/sets the location of a figure region as a proportion of the "drawing region" (which is usually the entire device, for single figure plots). It takes a length-4 vector of the form c(xmin, xmax, ymin, ymax) consisting of numbers (proportions) between 0 and 1.

Here I use grconvertX() and grconvertY() to convert x-y locations expressed in terms of the larger plot's own (a.k.a. "user") coordinate system into the "ndc" (normalized device coordinates) coordinate system. The "user" coordinate system is more human-user-friendly, while the "ndc" is (with the caveats expressed above) the coordinate system used by par("fig"). The grconvert*() calls are just there to perform the translation between them.

## pdf("fig-in-fig.pdf", width=10, height=10)
curve(exp(x), from=1, to=5, lwd=5)
curve(150-exp(x), from=1, to=5, lwd=5, col="darkblue",add=T)

## Here's the bit I added.
par(fig = c(grconvertX(c(1, 3), from="user", to="ndc"),
            grconvertY(c(50, 125), from="user", to="ndc")),
    mar = c(4,6,1,1),
    new = TRUE)

curve(exp(x), from=1, to=5, lwd=7, xlab="chi", ylab="exp(x)", cex.lab=4,axes=F)
axis(1, labels=NA,at=c(0,5))
axis(2, labels=NA,at=c(0,150))
text(1,120,"Alpha",adj=c(0,0),cex=3)
text(3.5,10,"Beta",adj=c(0,0),cex=3)
## dev.off()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...