3

I have the following data frame (df1) which i generated a geom_tile plot from it.

X Y Z
1 1 0.343
5 4 0.134
10 6 0.564
20 8 0.532
40 9 0.235
46 12 0.425

and i have another data frame which i want to use to draw the lines (df2):

a b c     d
1 1 0.05 good
5 4 0.01 better
10 6 0.03 middle
20 8 0.1  bad
40 9 0.2  bad
46 12 0.22 bad

so the idea, is that a and X are the same and b and Y are the same values.

what i want to do is to draw some lines around the geom_tile areas depending on the value of d in df2. so in each different area there will be a different color line e.g (good is red, better is blue, ...)

i tried to use geom_contour but the problem it draws lines in a very ugly way and i wasn't able to specify coordinates in a good way ..

Note

  • some areas might not be in straight lines
  • data frames are bigger, this is a test data to explain the idea
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
ifreak
  • 1,726
  • 4
  • 27
  • 45

1 Answers1

3

I would suggest, first, to merge both data frame together as they have the same values in two columns.

 df.new<-merge(df1,df2,by.x=c("X","Y"),by.y=c("a","b"))
 df.new
   X  Y     Z    c      d
1  1  1 0.343 0.05   good
2 10  6 0.564 0.03 middle
3 20  8 0.532 0.10    bad
4 40  9 0.235 0.20    bad
5 46 12 0.425 0.22    bad
6  5  4 0.134 0.01 better

Then in aes() set fill= for the Z (if necessary) and color=d. size=2 in geom_tile() will ensure that lines around tiles are better visible.

 ggplot(df.new,aes(X,Y,fill=Z,color=d))+geom_tile(size=2)

Similar results can be achieved also without merging data frame - you should use two geom_tile() calls (one for each data frame) and in second geom_tile() (where color is set) add fill=NA outside aes().

ggplot()+geom_tile(data=df1,aes(X,Y,fill=Z))+
         geom_tile(data=df2,aes(a,b,color=d),size=2,fill=NA)

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • thanks for your answer, but will this work for examle for multiple tiles together ? e.g big group of data which have a good value, will they be treated as one rectangle or square or whatever..besides i think this will not work when we have no straight lines – ifreak Apr 10 '13 at 10:05
  • since the data frames i have are much bigger as i wrote in the question, the geom_tiles are too small and in some case we have a cluster of geom_tiles which is not straight (rectangele or ...) it can be in weird shapes .. will this draw a line around them all together? or around each geom_tile a different contour ?? – ifreak Apr 10 '13 at 10:19
  • i've tried it, it does for each geom_tile a different contour .. which is not exactly what i want .. – ifreak Apr 10 '13 at 11:05
  • @ifreak Could add to your question some picture what exactly you want to achieve. If for example five points overlap - should they have the same line around (even if their d values are different)? – Didzis Elferts Apr 10 '13 at 11:51