0

I have a dataframe and I want to plot with geom_tile and fill according to the "ID" variable in the data, but I find that fill is not working in my code. Thanks for any help.

set.seed(1234)
x <- sample(x=-2288200:3076160, size = 1000,replace = F)
y <- sample(x=353334.1:4803914.0, size = 1000,replace = F)
ID <- sample(x=1:4, size = 1000,replace = T)
Mydata <- data.frame(x=x,y=y,ID=factor(ID))

group.colors <- c("1"="red","2"="yellow","3"="blue","4"="green")
ggplot() + geom_tile(data = Mydata, aes(x = x, y = y, fill=ID)) + 
  scale_fill_manual(values = group.colors,name = "group")

enter image description here

Yang Yang
  • 858
  • 3
  • 26
  • 49
  • Please provide a reproducible example without external data, for an example such as this one you can either start from a base dataset like `iris` or make one up, or provide an extract of your data – moodymudskipper Feb 09 '18 at 17:54
  • almost there :), please provide it as text so we can copy and paste it. It needs of course to be enough data to be usable to reproduce your issue. – moodymudskipper Feb 09 '18 at 17:59
  • this thread will explain it better than me: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – moodymudskipper Feb 09 '18 at 18:02
  • Thank you for your suggestion and I have edited the question. – Yang Yang Feb 09 '18 at 18:18
  • as I understand, `geom_raster` and `geom_tile` will compute height and width automatically when they're not provided. What height and width they choose might depend on the position of other data points. Your data being sparse, these are extremely small at the scale of the plot – moodymudskipper Feb 09 '18 at 18:39
  • try this: `ggplot(Mydata) + geom_tile(aes(x = x, y = y, fill=1),width=100000,height=100000) ` – moodymudskipper Feb 09 '18 at 18:41
  • Amazing! I do not know that we can set width and height in `geom_tile`! Could you formally answer the question so I can accept your answer? – Yang Yang Feb 09 '18 at 18:45

1 Answers1

2

geom_tile used without a height and width parameter will choose them automatically to create a grid.

In your case this grid is very narrow as your data is very sparse, so the tiles that you're trying to show are smaller than your resolution can show.

We can show their positions by assessing a width and height to the data points (though we're not showing a grid anymore in this case!).

ggplot(Mydata) + geom_tile(aes(x = x, y = y, fill=ID),width=100000,height=100000)

Compare it with:

Mydata2 <- data.frame(x=c(1,2,2.5,3),y=c(1,2,2.5,3),ID=1:4)
ggplot(Mydata2) + geom_tile(aes(x = x, y = y, fill=ID)) 
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167