How to resolve issue of an empty levelplot() in R?

1.6k views Asked by At

I am using levelplot() in R to generate a colored image of matrix (36 X 32). The matrix contains many NaN values in it. When I try to generate the levelplot using the following commands

range = c(815.4, 816.2)
matpalette <- colorRampPalette(c("blue", "black", "red"))(100)
levelplot(t(m1),scales = list(draw = FALSE), col.regions = matpalette, xlab = "", ylab = "", at = seq(min(m1), max(m1), length = 100), main=main)

I get the following error message:

Error in seq.default(min(m1), max(m1), length = 100) : 'from' cannot be NA, NaN or infinite

This error is understood. Instead of using min(m1) and max(m1) in the levelplot(), when I try using the following:

levelplot(m1,scales = list(draw = FALSE), col.regions = matpalette, xlab = "", ylab = "", at = seq(range[1], range[2], length = 100), main=main)

I get an empty plot, just with the colorbar and with the range specified as tick values.

enter image description here

What I need is a plot of the values in the matrix and the same colorbar and identical tick values as in the levelplot provided. Can anyone help me in this?

# Variant 2

 s <- seq(from=range[1], to=range[2], by=0.1)

 levelplot(t(m1), scales=list(tick.number=0), xlab=" ", ylab=" ", colorkey = list(at=s, labels=as.character(s)),col.regions = two.colors(n=256, start='blue', end='red', middle='black'), main=main)

The colorbar which I get is like this

enter image description here

Note: Range used is different

1

There are 1 answers

0
jlhoward On

Like this??

test <- read.csv("test.csv")
library(lattice)
library(colorRamps)  # for colorRampPalette
matpalette <- colorRampPalette(c("blue", "black", "red"))(100)
levelplot(as.matrix(test[,-1]),col.regions=matpalette)

Here's more or less the same thing using ggplot

library(ggplot2)
library(reshape2)    # for melt(...)
library(grid)        # for unit(...)
gg <- melt(test,id="X")
ggplot(gg,aes(x=X,y=variable,fill=value))+
  geom_tile()+
  scale_fill_gradientn(name="",colours=matpalette,na.value="white")+
  scale_x_continuous(expand=c(0,0))+
  scale_y_discrete(expand=c(0,0))+
  coord_fixed()+ theme_bw()+
  theme(legend.key.height=unit(.15,"npc"))