分类数据的水平图?

问题描述 投票:0回答:1

我想使用以下代码生成基于矩阵的水平图。

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="")

我的问题是关于传说的。 “值”定义为分类数据,如何将图例固定为离散标签。

r lattice
1个回答
0
投票

levelplot
似乎并不是为这样的分类图设计的。您 can
colorkey
参数中使用一些 hacky 技巧来获得这样的近似值:

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())

© www.soinside.com 2019 - 2024. All rights reserved.