Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a color frame to a plot?

Tags:

plot

r

For some reasons I want to add a frame to a plot like this:

enter image description here

Can I do this in plot? ggplot or qplot solutions are also welcome. Thank you.

like image 246
ziyuang Avatar asked Dec 09 '12 05:12

ziyuang


3 Answers

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

like image 144
IRTFM Avatar answered Oct 11 '22 15:10

IRTFM


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

enter image description here

like image 23
agstudy Avatar answered Oct 11 '22 15:10

agstudy


You can draw a solid rectangle, then using print(.., vp=..) plot your ggplot over it, shrinking it down slightly.

Here is an example in a nice little function:

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)

}

eg:

myPlot <- ggplot(iris,aes(Sepal.Length,Sepal.Width)) + 
                 geom_point(aes(color=Species,shape=Species))

borderize(myPlot, thick=5, color="#CF8042")

ggplot2 with border

Note that you can also modify plot.background and panel.background with theme() in ggplot2.
However, this will impact your labels and legend, depending on the thickness of border, font size etc. Thats why I prefer to use viewport.

eg:

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

red border is plot, blue border is panel

enter image description here
NOTICE HOW THE BORDER EATS INTO THE LABELS

The advantage of using plot.background however is that you can save the whole graph as an object; something you cannot do using the borderize method above.

like image 24
Ricardo Saporta Avatar answered Oct 11 '22 13:10

Ricardo Saporta