R lattice levelplot,改变背景颜色和自定义色标标签

R lattice levelplot, changing the background color and custom colorscale labels

我有一个格子图,我想改变它的背景,但似乎无法让它工作。我也在尝试添加自定义热图标签(范围从 1 到 5,并想添加一些文本。)

par(bg = "yellow")
levelplot(as.matrix(x = c(1:5),y = c(5:1))
)

感谢您的宝贵时间!

library(lattice)
trellis.par.set(background = list(col="yellow"))
levelplot(as.matrix(x = c(1:5),y = c(5:1)), 
          scales=list(x=list(at=1:5, labels=LETTERS[1:5])))

reprex package (v2.0.1)

创建于 2022-04-26

ggplot一样,lattice是基于网格图形,而不是基于R图形,所以设置par不会有任何效果。您可以更改晶格参数,或者您可以在事后使用 grid.edit:

进行更改
library(lattice)
library(grid)

levelplot(as.matrix(x = c(1:5), y = c(5:1)))
grid.edit("plot_01.background", gp = gpar(fill = "yellow"))

不用说,如果您正在寻找多种格式更改、简单的注释、自定义比例和丰富的文档,您应该切换到 ggplot:

library(ggplot)

ggplot(data.frame(x = 1:5), aes(x, 0.5, fill = x)) +
  geom_tile() +
  geom_text(aes(label = x), size = 10) +
  coord_equal() +
  scale_x_continuous(limits = c(0.5, 5.5), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0, 1), expand = c(0, 0)) +
  scale_fill_gradient2(low = "#ff77ff", mid = "white", high = "cyan",
                       midpoint = 3) +
  theme_classic(base_size = 18) +
  theme(plot.background = element_rect(fill = "#FFFF80"),
        plot.margin = margin(150, 50, 150, 50),
        legend.background = element_blank())