Mohammad - 1 year ago 137
R Question

# How to plot a shaded area on ggplot?

I have a plot in ggplot which the x axis is the real and y axis is imaginary values of my data. For example:

``````dat=data.frame(real=c(0,0.5,0.7),imaginary=c(0.7,0.5,0.5))
ggplot(dat,aes(real,imaginary))+geom_point(size=7)+xlim(0,1)+ylim(0,1)
``````

So the plot looks like:

Now I need to add a shaded area on the plot including the following functions ranges:

``````real = a*cos(b)         # 0<a<0.5  0<b<45
imaginary = a*sin(b)    # 0<a<0.5  0<b<30
``````

Thanks a lot

This seems to be more of a maths problem than a programming one. First determine what shape this will trace out (and it is not necessarily true that the coordinates will define a region that can be shaded in, but in this case they do), and then use e.g. `geom_polygon` to draw them.

It looks like you want to draw a circle centred at (0, 0) with radius 0.5, and fill it in. (your equation is `real^2 + imaginary^2 = a^2` which describes this circle. The fact that `a` goes from 0 to 0.5 just means you want every circle from radius 0 to radius 0.5. `b` defines how much of the circle you trace out, but once you hit 2*pi you will get a full circle anyway so going past that doesn't make a difference).

So you can just make a set of (x, y) coordinates on this circle e.g.

``````b <- seq(0, 2*pi, by=0.1) # sin/cos are periodic, no point going past 2*pi
circ <- data.frame(x=0.5*cos(b), y=0.5*sin(b))
``````

Original plot:

``````dat=data.frame(x=c(0,0.5,0.7),y=c(0.7,0.5,0.5))
p = ggplot(dat,aes(x,y))+geom_point(size=7)+xlim(0,1)+ylim(0,1)+xlab("real")+ylab("imaginary")
``````

so all you need is

``````p + geom_polygon(dat=circ)
``````

You can change the colour and so on. Now you'll notice that the circle looks odd in this graph - it's because the x and y limits are restricted from 0 to 1 while the circle covers a range more than this. If you use `xlim` and `ylim` ggplot will truncate the data (ie truncate the bits of the polygon causing it to look odd) rather than simply truncating the view window. To fix it, use `coord_cartesian` to restrict the axes rather than `xlim` and `ylim`.

``````ggplot(dat, aes(x, y)) + geom_point(size=7) +
coord_cartesian(xlim=c(0, 1), ylim=c(0, 1)) +
geom_polygon(dat=circ)
``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download