简体   繁体   中英

Heatmaps for a matrix with ones and zeros using R

Below is my sample data, basically its a matrix with row names as person names and some columns for each of these rows. All I have in the data is just zeros and ones. I would like to visualize it using heatmaps. (reds for 0s and green for 1s or any other color coding). How do I accomplish this using R? you can show me using any example dataset with just ones and zeros (binary values).

在此处输入图片说明

Just another approach using ggplot

library(ggplot2)
library(reshape2)
library(plyr)
library(scales)

df <- structure(list(people = structure(c(2L, 1L), .Label = c("Dwayne", "LeBron"), class = "factor"),
                 G = c(1L, 0L),
                 MIN = c(1L, 0L),
                 PTS = c(0L, 1L),
                 FGM = c(0L,0L),
                 FGA = c(0L,0L),
                 FGP = c(1L,1L)),
            .Names = c("people", "G", "MIN", "PTS", "FGM", "FGA", "FGP"),
            class = "data.frame",
            row.names = c(NA, -2L))


df.m <- melt(df)
df1.m <- ddply(df.m, .(variable), transform, rescale = value)
p <- ggplot(df1.m, aes(variable, people)) +
geom_tile(aes(fill = rescale), colour = "black")
p + scale_fill_gradient(low = "green", high = "red")
show(p)

Adopted from this tutorial

With highcharter:

library(highcharter)
library(tidyr)
library(dplyr)
df<-data.frame(row=c("Dwayne","James"),G=c(1,0),MIN=c(1,0),PTS=c(0,1),FGM=c(0,0),FGA=c(0,0),FGP=c(1,1))
rownames(df)<-c("Dwayne","James")
df$row<-rownames(df)
data<-df%>%
     tidyr::gather(row,value)%>%
     setNames(c("name","variable","value"))


hchart(data, "heatmap", hcaes(x = variable, y = name, value = value)) %>% 
  hc_colorAxis(stops = color_stops(2, c("red","green")))

在此处输入图片说明 UPDATE: You can add hc_size(height = 800) for height=800 or make something like that

  x<-50
  hg<-length(unique(data$name))*x+100

  hchart(data, "heatmap", hcaes(x = variable, y = name, value = value)) %>% 
    hc_colorAxis(stops = color_stops(2, c("red","green")))%>% 
    hc_size(height = hg)

Where each row in dataset makes chart bigger by 50 points. You can change it in x

This answer uses plotly and hence adding it as another answer. Using the same data as the following one.

library(plotly)
df1 <- as.matrix(df)
p <- plot_ly(x = colnames(df), y = df[,1], z = as.matrix(df[-1]), colors = colorRamp(c("green", "red")), type = "heatmap")

This is much simpler than the ggplot2 in terms of getting the output.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM