【问题标题】:How to resolve issue of an empty levelplot() in R?如何解决 R 中的空 levelplot() 问题?
【发布时间】:2015-01-30 22:25:43
【问题描述】:

我在 R 中使用 levelplot() 来生成矩阵 (36 X 32) 的彩色图像。矩阵中包含许多 NaN 值。当我尝试使用以下命令生成水平图时

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)

我收到以下错误消息:

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

可以理解这个错误。当我尝试使用以下内容时,而不是在 levelplot() 中使用 min(m1) 和 max(m1):

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

我得到一个空图,只有颜色条和指定为刻度值的范围。

我需要的是矩阵中的值的绘图,以及与提供的 levelplot 中相同的颜色条和相同的刻度值。任何人都可以帮助我吗?

# 变体 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)

我得到的彩条是这样的

注意:使用的范围不同

【问题讨论】:

  • 显然您的矩阵 m1 具有 NA 值。也许你应该使用min(m1, na.rm=TRUE)max(m1, na.rm=TRUE)
  • 另外:你确定m2 有任何介于 815.4 和 816.2 之间的值吗?因为这可以解释问题......
  • 是的,这就是问题所在。我尝试了您的建议并且它起作用了,但是现在在颜色栏的刻度线上,我得到了数据集中范围的值。最初,我使用#variant2(问题中插入的命令)来生成格点图。但是,在这种情况下,我得到了图像,但没有得到平滑的颜色条。
  • 在这种情况下如何获得平滑的颜色条?
  • 请添加矩阵以制作您的示例reproducible

标签: r matrix nan colorbar levelplot


【解决方案1】:

像这样??

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)

这里使用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"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多