Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make size of points scale with graph in ggplot2

Tags:

r

ggplot2

I'm wanting to draw a Hinton plot of a correlation matrix, and I can get 99% of the way, but when I set the size of the points I'm plotting, that size is in pixels and so doesn't scale as the graph size changes. How can I "calibrate" the size of the points to be a fraction of the size of the axes for example? I want it to be so that when I double the size of the graph the points double. I may be using the wrong geom.

I have this code so far:

library(ggplot2)
library(data.table)
library(reshape2)

DT = data.table(A = rnorm(10), B = rnorm(10), X = rnorm(10), Y = rnorm(10))
C = cor(DT)

ggplot(melt(C), aes(x=Var1, y=Var2, size=abs(value), color=as.factor(sign(value)))) +
  geom_point(shape = 15) +
  scale_size_area(max_size = 40) +
  theme_bw()

By changing the max_size for scale_size_area I can just about get the diagonals to fill the area, but if I change the size of the chart the points don't scale. Is there a way to force the points to take a particular size in axes coordinates? Ideally of course, I'd like to use rectangles so that I could have any shape and it still work, but I don't know of a geom that would do that?

enter image description here

like image 412
Corvus Avatar asked Oct 02 '22 22:10

Corvus


1 Answers

Just use as.numeric to turn Var1 & Var2 back to grid co-ordinates inside the geom_rect() function to draw rectangle over each intersect point. If you add 0.5 units * correlation to generate the max and min co-ords, they'll fit exactly for a value of 1, and shrink in proportion:

ggplot(melt(C)) +
  geom_point(aes(Var1,Var2)) +
  geom_rect(aes(xmin=as.numeric(Var1)-0.5*abs(value),xmax=as.numeric(Var1)+0.5*abs(value),ymin=as.numeric(Var2)-0.5*abs(value),ymax=as.numeric(Var2)+0.5*abs(value),fill=as.factor(sign(value)))) +
  theme_bw()

enter image description here

like image 60
Troy Avatar answered Oct 05 '22 08:10

Troy