[This article was first published on sigmafield - R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Last night, while working on something else that I want to finish, I ended up indulging in a bit of “yak shaving”. I wondered how easy it would be to generate graphics in ggplot2 with rounded corners. I don’t think that there is any native support for this in the theming system. Therefore, I had to descend into the depths of R’s grid graphics system. Luckily, I have read Paul Murrell’s beyond excellent R Graphics book, so I was prepared for the venture.

Making my task even easier was the fact that there now exists the functionality in grid to generate rectangles with rounded corners. This is accomplished with the `grid.roundrect` and corresponding `roundrectGrob` functions.

So, here is my first attempt.

```library(ggplot2)
p <- qplot(carat, price, data = diamonds[sample(1:nrow(diamonds), 100),]) +
geom_smooth()

grob <- ggplotGrob(p)
plot.rrg <- roundrectGrob(gp = gpar(fill = "skyblue1", col = NA),
r = unit(0.06, "npc"))

grob <- removeGrob(grob, "plot.background.rect",
grep = TRUE)

grid.draw(gList(plot.rrg, grob))

```

As you see, the objective was achieved, but not nearly as cleanly as I'd like. Essentially, I'm relying on a trick by removing the plot rectangle grob and creating a new one in a gList. This happens to work since the new round rectangle is drawn first. Ideally, I'd like to add the new rounded rectangle grob into the gTree object in the 'proper' place, i.e., where the original `plot.background.rect` rectangle was. I assume that is possible if I investigate further. It was not obvious to me how to do that though. Also, if I wanted the panel rectangle (grey colored in the figure) to be rounded, I believe I would have to find a way to replace that grob with a rounded rectangle at its original location.

So, that was a quick first attempt. The plot was saved using the `png` function with a transparent background. I will update this post if I find a cleaner solution. Please let me know if you are aware of how to add grobs in specific locations in a gTree, since that is what I am assuming I need to do.

## Tags:

To leave a comment for the author, please follow the link and comment on their blog: sigmafield - R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

# Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts.(You will not see this message again.)

Click here to close (This popup will not appear again)