R语言 向图像添加颜色图例

t3irkdon  于 2023-10-13  发布在  其他
关注(0)|答案(4)|浏览(108)

我有一个矩阵,我用image(matrix)做了一个图像。有没有办法添加一个传奇的颜色到我的形象,就像我这样做时,添加一个传奇的情节?

bvhaajcl

bvhaajcl1#

或者图例可以这样提供:

legend(grconvertX(0.5, "device"), grconvertY(1, "device"), 
     c("0",".5","1"), fill = colMap[c(1, 10, 20)], xpd = NA)

其中grconvertX()和grconvertY()和xpd确保图例在绘图区域之外。一个合理的例子是:

nsamples <- 20
    mat <- rnorm(nsamples, .5, .15)
    dim(mat) <- c(4, 5)
    colMap <- colorRampPalette(c("red","white","blue" ))(nsamples)
    image(1:4, 1:5, mat, col = colMap, ylab="", xlab="")
    legend(grconvertX(0.5, "device"), grconvertY(1, "device"),
    c("0",".5","1"), fill = colMap[c(1, 10, 20)], xpd = NA)

p. s.:我知道这是一个旧的请求,它已经解决了。我一直在寻找一个类似的答案,却找不到。既然我不想解决这个问题,我想也许其他人也可以从中受益。

uklbhaso

uklbhaso2#

image在R中是一个相当基本的绘图函数。如果你想要一个自动为图例分配空间的函数,你可能想看看filled.contour。或者试试这个:

library(lattice)
 levelplot(matrix)
l7mqbcuq

l7mqbcuq3#

fields包中,您可以尝试image.plot。此函数基于常规image,但它提供了图例。

library(fields)
x = 1:10
y = 1:15
z = outer( x,y,"+") 
image.plot(x, y, z)
tag5nh1u

tag5nh1u4#

要制作渐变色条,您可以这样做:

# make example data and color key
x <- matrix(data = sample(x = 5:85, size = 100, replace = T), nrow = 10)
n.colors <- 90
color.fun <- colorRampPalette(colors = c("magenta2", "grey"), bias = 10)
col.key <- data.table("color" = color.fun(n = n.colors),
                      "value" = seq(from = min(x), to = max(x), along.with = 1:n.colors))

# make the plot with image- leaving space for legend using fig
par(fig = c(0,.9,0,1), mar = c(2,2,2,0))
image(z = t(x), axes = F, ann = F, col = col.key$color)

# add the legend
par(fig = c(.9,1,.3,.7), mar = c(1,1,1,2.5), new = T)
plot(x = rep(1,length(col.key$value)), y = col.key$value, xlim = c(0,1), col = col.key$color, type = "n", xaxs = "i", yaxs = "i", ann = F, axes = F)
segments(x0 = 0, x1 = 1, y0 = col.key$value, y1 = col.key$value, col = col.key$color, lwd = 5)
axis(side = 4,lwd = 0, las = 2, line = -.75)
mtext(text = "Legend", adj = 0, line = 1, cex = 1.2)

请注意,这也解决了我认为HelloWorld的答案中的一个错误,因为您希望颜色在颜色条和图像之间精确Map(因此比例必须与实际数据值匹配)。

相关问题