0

I am trying to order a heat map in geom_tile()

 x <- structure(list(id = c("1", "1", "1", "2", "2", "3", "3", "3"), 
                     time = c("1", "2", "3", "1", "3", "1", "2", "3"), 
                     response = c( "0", "1", "1", "1", "1", "0", "0", "1")), 
                .Names = c("id", "time", "response"), class = "data.frame")

df %>%  
  ggplot() + geom_tile(aes(time, id, fill=response)) 

id is numeric and time and response are factors. My heat map should have id on the y-axis and time on the x-axis. I'm trying to group sets of responses so that each line is an id but that id's who follow the same pattern of 0,0,0 for the time periods are grouped together in blocks. I've tried order, reorder, and scale_y_continuous, but none of them change the order of responses.

This answer comes close to what I'm looking for, but none of the answers seem to work.

AstraOK
  • 49
  • 9

1 Answers1

0

I don't know if I understand your question correctly. What I observed that your sample data does not let you make any order.

Sample data:

id = c(1, 1, 1, 2, 2,2, 3, 3, 3) 
time = c(1, 2, 3, 1, 3,2, 1, 2, 3) 
response = c(0, 1, 1, 1, 1, 0, 0, 1)

df=cbind(id,time, response)
df<-as.data.frame(df)

df$id <- factor(df$id, levels=c("1", "2", "3"))
df$time <- factor(df$time, levels=c("1", "2", "3"))
df$response<- factor(df$response, levels=c("0", "1"))


df
  id time response
1  1    1        0
2  1    2        1
3  1    3        1
4  2    1        1
5  2    3        1
6  2    2        0
7  3    1        0
8  3    2        1
9  3    3        0

Sample code:

df$id<- factor(df$id, levels=unique(df$id[order(df$response)]))



ggplot(df, aes(time,id, fill=response)) + 
  geom_tile()+
  labs(x="Time",y="Id")+
  theme_minimal()

Plot: enter image description here

Well, based on what you suggest I think the relevant change would be

 df$id<- factor(df$time, levels=unique(df$id[order(df$time)]))

I also had to improve the data again

Sample data:

 id = c(1, 1, 1, 2, 2,2, 3, 3, 3, 2) 
time = c(1, 2, 3, 1, 3,2, 1, 2, 3, 2) 
response = c(0, 1, 1, 1, 1, 0, 0, 1,0,0)

df=cbind(id,time, response)
df<-as.data.frame(df)


df
   id time response
1   1    1        0
2   2    2        1
3   3    3        1
4   1    1        1
5   3    3        1
6   2    2        0
7   1    1        0
8   2    2        1
9   3    3        0
10  2    2        0

enter image description here

Rfanatic
  • 2,224
  • 1
  • 5
  • 21
  • Thanks! This is close. What I'd like in the plot is to group id's by time and by response so that the 0 responses (red in your plot) are grouped together in blocks. Here the y axis would be ordered as 1, 3 ,2 for example. – AstraOK Mar 08 '22 at 14:18
  • @AstraOK new edits – Rfanatic Mar 08 '22 at 14:56