英文:
Levelplot for categorical data?
问题
I want to produce a levelplot based on a matrix with 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.
英文:
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.
答案1
得分: 0
levelplot
似乎不太适用于这种分类瓷砖图。您可以在 colorkey
参数中使用一些巧妙的技巧来获得类似的近似效果:
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')))
我认为您可以使用 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())
英文:
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论