For some reasons I want to add a frame to a plot like this:
Can I do this in plot
? ggplot
or qplot
solutions are also welcome. Thank you.
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)
qplot(x= disp , y = wt , data = mtcars) +
theme(plot.background = element_rect(colour="#CF8057",size=10))
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)
}
myPlot <- ggplot(iris,aes(Sepal.Length,Sepal.Width)) +
geom_point(aes(color=Species,shape=Species))
borderize(myPlot, thick=5, color="#CF8042")
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With