Say we have some data like so:
df <- as.data.frame(matrix(ncol=4, nrow=12))
colnames(df) <- c("week", "hour", "fill", "day")
df$day <- rep(c("S", "S", "M", "M", "T", "T"), 2)
df$hour <- rep(seq(1,2,1),6)
df$week <- c(rep(seq(3,4,1),3), rep(seq(5,6,1), 3))
df$fill <- seq(1,120, 10)
print(df)
week | hour | fill | day |
---|---|---|---|
3 | 1 | 1 | S |
4 | 2 | 11 | S |
3 | 1 | 21 | M |
4 | 2 | 31 | M |
3 | 1 | 41 | T |
4 | 2 | 51 | T |
5 | 1 | 61 | S |
6 | 2 | 71 | S |
5 | 1 | 81 | M |
6 | 2 | 91 | M |
5 | 1 | 101 | T |
6 | 2 | 111 | T |
And we go to plot it with ggplot2.
ggplot(df, aes(x=hour, y =day, fill=fill))+
geom_tile()+
scale_x_continuous(breaks=seq(1,10,1))+
scale_fill_viridis_c()
How does ggplot decide what to fill each "point" with? In this case, the "point" at 1, M is equal to both 21 and 81 in the dataframe.
ggplot
doesn't need to decide which fill value to draw. It draws them all. The tiles are opaque, so you can only see the last tile drawn in a particular position. Typically this is just down to where the data point is within your data frame, with the points coming later being drawn on top of those that come first.
We can see this by simply inverting our data frame. In the default ordering we see only the last 6 rows:
ggplot(df, aes(x=hour, y =day, fill=fill))+
geom_tile()+
scale_x_continuous(breaks=seq(1,10,1))+
scale_fill_viridis_c(limits = c(0, 120))
But if we reverse the rows we see the first 6:
ggplot(df[12:1, ], aes(x=hour, y =day, fill=fill))+
geom_tile()+
scale_x_continuous(breaks=seq(1,10,1))+
scale_fill_viridis_c(limits = c(0, 120))
To show that the twelve tiles are all really "there", we can build the plot into a grob tree (as ggplot does during its print method):
p <- ggplot(df, aes(x=hour, y =day, fill=fill))+
geom_tile()+
scale_x_continuous(breaks=seq(1,10,1))+
scale_fill_viridis_c(limits = c(0, 120))
g <- ggplot_gtable(ggplot_build(p))
If we locate the rectgrob
s used to display our tiles, we will see that there are twelve of them. For example, here are the graphical parameters for all 12:
g$grobs[[6]]$children[[3]]$gp
#> $col
#> [1] NA NA NA NA NA NA NA NA NA NA NA NA
#>
#> $fill
#> [1] "#440556" "#46256B" "#433D80" "#3E5489" "#36698C" "#2B7E8D" "#2B9289" "#23A684" "#50B773"
#> [10] "#6EC85E" "#99D64A" "#D0E03A"
#>
#> $lwd
#> [1] 0.2845276 0.2845276 0.2845276 0.2845276 0.2845276 0.2845276 0.2845276 0.2845276 0.2845276
#> [10] 0.2845276 0.2845276 0.2845276
#>
#> $lty
#> [1] 1 1 1 1 1 1 1 1 1 1 1 1
#>
#> $linejoin
#> [1] "mitre"
#>
#> $lineend
#> [1] "butt"
Created on 2022-05-17 by the reprex package (v2.0.1)