0

I have a data frame full of 0 and 1 (example below) and I would like to create a plot with: 1 box = 1 year and if the value = 0, the box is empty, if it equals 1, it's filled in by a colour.

I searched with ggplot2 and tried to do a heat map but it's only for continuous variable, so it didn't work. I don't think this type of plot is possible with basic R, so if you have any idea!

The result could be like this (made with excel):

enter image description here

   An    Qobs Q_mm Ptot Temp PE
1  1958    0    0    0    0  0
2  1959    1    1    1    1  1
3  1960    1    1    1    1  1
4  1961    1    1    1    1  1
5  1962    1    1    1    1  1

Sorry for the title, it's not very explicit but didn't know what to write.

Jude
  • 153
  • 2
  • 8
  • 1
    Use ggplot's [geom_tile()](https://ggplot2.tidyverse.org/reference/geom_tile.html) (see examples on that page). Show what you attempted and show exactly where you are getting stuck. – MrFlick Aug 09 '18 at 16:00
  • @MrFlick My code was `ggplot(lacune, aes(lacune$An, lacune$Qobs)) + geom_tile(aes(fill=1), colour="black") + facet_grid(lacune$Qobs~lacune$An)` which created a weird plot ! – Jude Aug 10 '18 at 06:59
  • An important rule when working with `ggplot` is to never use `$` inside of `aes()` statements or formulas. You should always pass a `data=` parameter. See: https://stackoverflow.com/questions/32543340/issue-when-passing-variable-with-dollar-sign-notation-to-aes-in-combinatio – MrFlick Aug 10 '18 at 16:00

1 Answers1

1

First, you need to reshape your data, which can be accomplished using gather, then you can supply the data to ggplot2, and use `geom_tile. The other portions of your plot are aesthetic changes, which can be found by looking at the documentation for ggplot2.

library(tidyverse)

dat %>%
    gather(col_name, value, -An) %>%
    ggplot(aes(factor(An), col_name, fill = value == 1))+
    geom_tile(colour = 'black')+
    scale_fill_manual(values = c('FALSE' = 'white', 'TRUE' = 'blue'))

enter image description here

data

dat <- read.table(text = "   An    Qobs Q_mm Ptot Temp PE
1  1958    0    0    0    0  0
2  1959    1    1    1    1  1
3  1960    1    1    1    1  1
4  1961    1    1    1    1  1
5  1962    1    1    1    1  1")
bouncyball
  • 10,631
  • 19
  • 31