Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust the point size to the scale of the plot in ggplot2?

Tags:

plot

r

ggplot2

Let's generate some data:

x <- -10*cos(seq(0, pi, length.out = 100))+1
y <- 10*seq(0, pi, length.out = 100)
xerr <- rep(2, 100)
yerr <- rep(2, 100)
dd <- as.data.frame(cbind(x, y, xerr, yerr))

Here I have x and y coordinates of some points with their errors, xerr and yerr (for convenience I have set them constant). I would like to represent these errors with the size of the points. This is easily doable:

ggplot() + 
  geom_point(data = dd, aes(x, y, size = sqrt(xerr^2 + yerr^2)), colour = "gray") +
  geom_path(data = dd, aes(x, y), colour = "red", size = .5) +
  scale_size_identity() +
  theme_bw()

enter image description here

However, the size of these points is defined on a scale that doesn't have any relation with the scale of the plot. Is there a way to adjust the dimension of the points in relation to the scale of the plot? In the above example, the radius of each point should have size equal to 2.828 and not less than one as it is now.

like image 775
VLC Avatar asked Oct 16 '13 16:10

VLC


1 Answers

One way is to explicitly draw ellipses with the axes defined by the size of the errors.

x <- -10*cos(seq(0, pi, length.out = 10))+1
y <- 10*seq(0, pi, length.out = 10)
xerr <- runif(10, 1, 5)
yerr <- runif(10, 1, 5)
dd <- as.data.frame(cbind(x, y, xerr, yerr))
dd$frame <- factor(seq(1:10))

For this purpose we define our function to generate ellipses:

ellipseFun <- function(center = c(0, 0), axes = c(1, 1), npoints = 101){
  tt <- seq(0,2*pi, length.out = npoints)
  xx <- center[1] + axes[1] * cos(tt)
  yy <- center[2] + axes[2] * sin(tt)
  return(data.frame(x = xx, y = yy))
}

We then generate the matrices for all ellipses:

ddEll <- data.frame()
for(k in levels(dd$frame)){
  ddEll <- rbind(ddEll, cbind(as.data.frame(with(dd[dd$frame == k,], ellipseFun(center = c(x, y), axes = c(xerr, yerr), npoints = 101))),frame = k))
}

And, finally, we can plot them:

library(ggplot2)
ggplot() + 
  geom_point(data = dd, aes(x, y)) +
  geom_polygon(data=ddEll, aes(x = x, y = y, group = frame), colour = "gray", fill = "red", alpha = .2) +
  scale_size_identity() +
  theme_bw() +
  xlim(c(-20, 20)) + 
  ylim(c(-5, 35)) +
  coord_fixed()

enter image description here

like image 80
VLC Avatar answered Sep 27 '22 02:09

VLC