firmo23
firmo23

Reputation: 8404

Create a binary heatmap based on variables relationship

I have the dataframe below

DrugName <- c("as","df","fg","gh","jk")
value <- c("AD","AD","AD","AD","SEL")
MELT <- data.frame(DrugName, value)

and I want to create a heatmap that will have drug names as rows , and target symbols as columns (below the heatmap) and a grid square should be white if there is no association between a drug & a target or black if there is an association between a drug & a target. I use:

library(ggplot2)
ggplot(MELT, aes(value, DrugName)) +
 geom_tile() +
 geom_tile(aes(fill = value), colour = "white") + 
 scale_fill_manual(values = c("white", "black"))

and I get: enter image description here

I do not understand why the plot seems to have 3 column while the values are 2 and also why the coloring seems to be incorrect.

Upvotes: 1

Views: 855

Answers (1)

Henrik
Henrik

Reputation: 67778

Use table to count each combination of 'DrugName' and 'value', convert to data.frame. Map fill to a discrete version of 'Freq'.

In the example, the counts are only 0 or 1, and you can map fill color with fill = factor(Freq). If 'Freq' also has values > 1, then you may coerce to a binary version of 'Freq': fill = Freq != 0.

ggplot(data.frame(table(MELT)), aes(value, DrugName, fill = factor(Freq))) +
  geom_tile(color = "grey") +
  scale_fill_manual(values = c("white", "black"))

enter image description here

Upvotes: 2

Related Questions