Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting regions of interest in ggplot2

Tags:

r

ggplot2

In vanilla plotting, it is possible to use a polygon call in the panel.first argument to plot to highlight a background region. Is it possible to do the same in ggplot2? Can it be done while preserving the gridlines?

eg:

# plot hp and wt for mtcars data, highlighting region where hp/wt ratio < 35
with(mtcars,plot(hp,wt,
     panel.first=polygon(c(0,0,max(wt)*35),c(0,max(wt),max(wt)),
     col="#d8161688",border=NA)))
like image 910
James Avatar asked Aug 31 '10 15:08

James


People also ask

How do I highlight certain data points in R?

We can use the new data frame containing the data points to be highlighted to add another layer of geom_point(). Note that we have two geom_point(), one for all the data and the other for with data only for the data to be highlighted.

What does %>% do in ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

Can you filter within ggplot?

ggplot2 allows you to do data manipulation, such as filtering or slicing, within the data argument.


1 Answers

Yes, that's possible with ggplot2. To preserve the visibility of grid lines you can use alpha transparency. Note that, in general, the order in which geoms and stats are applied matters.

tmp <- with(mtcars, data.frame(x=c(0, 0, max(wt)*35), y=c(0, max(wt), max(wt))))
ggplot(mtcars, aes(hp, wt)) + 
  geom_polygon(data=tmp, aes(x, y), fill="#d8161688") + 
  geom_point()

ggplot2 output

like image 172
rcs Avatar answered Oct 17 '22 01:10

rcs