ndichistan
ndichistan

Reputation: 47

geom_tile in ggplot2 returning blank plot

I am trying to plot a dataset with three columns using the code below, but I get a blank figure with just the names on the axis, can anyone tell me what I am doing wrong?

#rm(list=ls())
library(data.table)
library(wesanderson)
library(ggplot2)

exa <- fread("sample.csv", sep = "," ,header = T,  stringsAsFactors = FALSE)

pal <- wes_palette("Zissou1", 100, type = "continuous")
sp1<-ggplot(exa, aes(x=x, y=y, fill=z))+
geom_tile(show.legend = T)+
scale_fill_gradientn(colours = pal) + 
  scale_x_discrete(expand = c(0, 0)) +
  scale_y_discrete(expand = c(0, 0)) 
sp1

Data:

exa <- structure(list(x = c(0.457744, 0.492325, 0.49948, 0.471712, 0.504126, 
0.505528, 0.516318, 0.521419, 0.518354, 0.523001, 0.527301, 0.566585, 
0.411753, 0.427226, 0.446747, 0.43778, 0.432248, 0.444912, 0.462414, 
0.456952, 0.443462, 0.420683, 0.392057), y = c(25.69908, 25.65119, 
25.8332, 23.88982, 22.41502, 22.27553, 23.05898, 24.20714, 25.23666, 
25.35443, 25.78347, 27.20575, 20.94434, 21.62892, 22.61483, 22.49146, 
23.38523, 24.46414, 25.8023, 26.63754, 27.40164, 27.45981, 27.97814
), z = c(29.75408, 29.02752, 28.43744, 27.98952, 27.62504, 27.32658, 
27.04928, 26.77825, 26.53036, 26.28481, 26.04137, 25.80254, 28.5918, 
27.81994, 27.44201, 27.15059, 26.83333, 26.54576, 26.31531, 26.12999, 
25.88431, 25.65788, 25.47488)), class = "data.frame", row.names = c(NA, 
-23L))

Upvotes: 0

Views: 1034

Answers (1)

chemdork123
chemdork123

Reputation: 13863

Well, like others said, it's probably not the preferred way to represent your data in tiles, but rather use geom_point. In that case, here's something that works:

ggplot(exa, aes(x,y,color=z)) +
  geom_point(size=3) +
  scale_color_gradientn(colors = pal)

enter image description here

If you still want to use tiles, as others mentioned, you cannot see the tiles because theya are just too small. You can make them larger to see by specifying width= and height=. Since your scales for x and y axis are different, you can't specify the same number if you want square-ish tiles. For that, you can use a bit 'o math to do that for you. Here's something that works:

w= 0.02 * (max(exa$x)-min(exa$x))
h= 0.02 * (max(exa$y)-min(exa$y))

ggplot(exa, aes(x,y,fill=z)) +
  geom_tile(width=w, height=h) +
  scale_fill_gradientn(colors = pal)

enter image description here

BTW - the tiles there are still not square due to the aspect ratio of the plot.

Upvotes: 2

Related Questions