由于某些原因,我想在这样的情节中添加一个框架:
我可以在plot
中执行此操作吗?我们也欢迎ggplot
或qplot
解决方案。谢谢。
答案 0 :(得分:6)
set.seed(123);
plot(x=rnorm(100, sd=1000), y=rnorm(100, sd=1000) ,ylab="", xlab="")
rect(xleft=par("usr")[1]*1.25, ybottom=par("usr")[3]*1.4,
xright=par("usr")[2]*1.1,ytop=par("usr")[4]*1.2,
lwd=5, border="orange", xpd=TRUE)
答案 1 :(得分:3)
你可以绘制一个实心矩形,然后用print(.., vp=..)
绘制你的ggplot,稍微缩小它。
这是一个很好的小函数的例子:
borderize <- function(plotObj, thick=2, color="orange", alpha=0.8) {
# thick should be a value between (1, 100)
# alpha should be a value between (0, 1)
# these could be modified for separate width/height thicknesses
wd <- ht <- (100 - thick) / 100
x <- (1 - wd) / 2
y <- (1 - ht) / 2
# create a solid rectangle. The plot will go over it.
grid.rect(y = 1, height = 1, just = c("center", "top"), gp=gpar(fill=color, alpha=alpha, lwd=0))
# create the viewport
vp.inner <- viewport(height=unit(ht, "npc"), width=unit(wd, "npc"), just=c("left","bottom"), y=y, x=x)
print(plotObj, vp=vp.inner)
}
myPlot <- ggplot(iris,aes(Sepal.Length,Sepal.Width)) +
geom_point(aes(color=Species,shape=Species))
borderize(myPlot, thick=5, color="#CF8042")
请注意,您还可以使用ggplot2中的theme()修改plot.background
和panel.background
。
但是,这会影响标签和图例,具体取决于边框的粗细,字体大小等。
这就是为什么我更喜欢使用视口。
例如:
plot.bg <- theme(plot.background=element_rect(color="red", size=12))
panel.bg <- theme(panel.background=element_rect(color="blue", size=12))
plotObj + panel.bg + plot.bg
红色边框为plot
,蓝色边框为panel
通知标签如何进入标签
使用plot.background
的优点然而,您可以将整个图形保存为对象;使用上面的borderize
方法无法做到的事情。
答案 2 :(得分:3)
qplot(x= disp , y = wt , data = mtcars) +
theme(plot.background = element_rect(colour="#CF8057",size=10))