I want to produce a levelplot based on a matrix with the the following code.
library("lattice")
x<-c(0:10)
y=seq(0,0.9,by=0.1)
z <- expand.grid(cost_hs, rr_ls)
val<-sample(c("A","B","C"),110,replace = T)
z$value=as.factor(val)
levelplot(value ~ Var1*Var2,data=z,main="")
My question is about the legend. The "value" is defined as categorical data, how to fix the legend as discrete label.
levelplot
doesn't really seem to be designed for categorical tile plots like this. You can use some hacky tricks in the colorkey
argument to get an approximation like this:
levelplot(value ~ Var1 * Var2, data = z, main = "", regions = TRUE,
colorkey = list(at = c(0.5, 1, 1.5, 2, 2.5, 3, 3.5),
labels = c('', 'A', '', 'B', '', 'C', ''),
col = c('#ff80ff', '#ff80ff', 'white',
'white', '#80ffff', '#80ffff')))
I think you would get a better result using ggplot
:
library(ggplot2)
ggplot(z, aes(Var1, Var2, fill = value)) +
geom_tile() +
scale_fill_manual(values = c(A = '#ff80ff', B = 'white', C = '#80ffff')) +
theme_classic(base_size = 16) +
coord_cartesian(expand = FALSE) +
theme(panel.border = element_rect(fill = NA),
axis.line = element_blank())