如何在绘图中添加颜色框?

时间:2012-12-09 05:15:19

标签: r plot

由于某些原因,我想在这样的情节中添加一个框架:

enter image description here

我可以在plot中执行此操作吗?我们也欢迎ggplotqplot解决方案。谢谢。

3 个答案:

答案 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)

enter image description here

答案 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 with border

请注意,您还可以使用ggplot2中的theme()修改plot.backgroundpanel.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

enter image description here
通知标签如何进入标签

使用plot.background优点然而,您可以将整个图形保存为对象;使用上面的borderize方法无法做到的事情。

答案 2 :(得分:3)

qplot(x= disp , y = wt , data = mtcars) +
  theme(plot.background = element_rect(colour="#CF8057",size=10))

enter image description here