R heatmap ggplot2 ordered as data file

2019-08-01 21:39发布

问题:

I'm producing this heatmap

How to produce a heatmap with ggplot2?

The code in that post works fine

library(reshape2)
 library(ggplot2)
 library(scales)
library(plyr)
data <- read.csv("fruits.txt", head=TRUE, sep=",")
 data.m = melt(data)
 data.m <- ddply(data.m, .(variable), transform, rescale = rescale(value))
  data.m <- ddply(data.m, .(variable), transform, rescale = rescale(value))
 p <- ggplot(data.m, aes(variable, people)) + geom_tile(aes(fill = rescale), 
                                                   colour =   "white") 
 p + scale_fill_gradient(low = "white", high = "steelblue")

The data file I'm using is this

people,1,2,3
Ej1,1,0,0
Ej2,0,0,1
Ej3,0,0,1
Ej4,1,1,0

But I need to show the rows as they are (starting from Ej1 to Ej4) and it produces them in reverse order, I can't find out how to show them as they are in the data file.

回答1:

Like this?

Try using:

data$people <- factor(data$people,levels=rev(data$people))

just before the call to melt(...):

data$people <- factor(data$people,levels=rev(data$people))
data.m = melt(data)
data.m <- ddply(data.m, .(variable), transform, rescale = rescale(value))
p <- ggplot(data.m, aes(variable, people)) + geom_tile(aes(fill = rescale), 
                                                       colour =   "white") 
p + scale_fill_gradient(low = "white", high = "steelblue")

data$people is a factor and ggplot will order the factor levels alphabetically "increasing" from bottom to top. The change above reverses the order of the factor levels.



标签: r ggplot2