[R] Using factor levels as coordinates with geom_rect

Loris Bennett loris.bennett at fu-berlin.de
Wed Sep 24 10:39:00 CEST 2014


Loris Bennett <loris.bennett at fu-berlin.de> writes:

> Hi,
>
> With ggplot2 I can use the following to create a rectangle 
>
> geom_rect(aes(ymin=as.Date("8-Apr-2014", format="%d-%b-%Y"),
>                 ymax=as.Date("30-Apr-2014", format="%d-%b-%Y"),
>                 xmin="node002",xmax="node098"),
>
> where the x values are levels of a factor.  This works if I want the
> rectangle to extend across a range of factor level.  My question is this:
>
> How can I create a similar rectangle around a single factor level?
>
> My assumption is that I should be able to convert the factor to a
> numerical value.  I could then subtract and add a smaller number to
> obtain xmin and xmax, respectively.  However, I don't know how to
> convert the factor level to a value which corresponds to its
> x-coordinate on the plot.
>
> I posted a longer version of this question on StackOverflow with the
> full code, input data, and a plot of the output:
>
> http://stackoverflow.com/questions/25872633/using-factor-levels-with-geom-rect
>
> Unfortunately, I didn't get an answer.
>
> Cheers,
>
> Loris

I was sent a comment via email which helped me along.  The gist was that
factor levels are internally converted to integers for plotting
purposes.  Thus, I just needed to extract the correct integers for the
level I was interested in.

I did this by creating a sorted list of the factor levels:

  nodelist <- sort(levels(flatdata$value))

and then extracted the index corresponding to the level by using
'which'.  I could then construct the rectangle with the following:

  geom_rect(aes(ymin=as.Date("8-Apr-2014", format="%d-%b-%Y"),
                ymax=as.Date("30-Apr-2014", format="%d-%b-%Y"),
                xmin=which(nodelist=="node004")-0.5,
                xmax=which(nodelist=="node004")+0.5,
                fill="red", alpha=0.25))

Cheers,

Loris

-- 
This signature is currently under construction.



More information about the R-help mailing list