我想生成这样的图像:
其中像素颜色由多元正态分布的值确定。换句话说,我有以下数据框:
images <- data.frame(x = rnorm(256*256*20), image = rep(c(1:20), each = 256*256))
我想绘制来自多元法线的20个绘制向量中的每一个,作为彩色方块。方块应在2x10网格上对齐。它们是否被黑线分开并不重要,但不同方块之间必须存在某种分离。值0应对应于浅灰色或白色(灰色会更好)。我怎样才能做到这一点?我想要一个ggplot
解决方案,但只要代码相当灵活和可读(性能不是问题),基本R或其他东西也是好的。
编辑广场不一定是256 * 256,64 * 64也不错。
答案 0 :(得分:1)
这是一次尝试:
生成r,g,b通道:
library(tidyverse)
images <- data.frame(r = rnorm(256*256*20),
g = rnorm(256*256*20),
b = rnorm(256*256*20),
image = rep(c(1:20), each = 256*256))
将rgb转换为十六进制的函数:
rgb2hex <- function(r,g,b) rgb(r, g, b, maxColorValue = 255)
将rnorm
的0均值和1 sd转换为r,g,b通道,重新缩放到0-1范围并乘以255,最后转换为十六进制
images %>%
group_by(image) %>%
mutate(y = rep(1:256, each = 256), #x coords
x = rep(1:256, times = 256), #y coords
r = round(scales::rescale(r) * 255, 0),
g = round(scales::rescale(g) * 255, 0),
b = round(scales::rescale(b) * 255, 0),
hex = rgb2hex(r, g, b)) -> for_plot
ggplot(for_plot) +
geom_raster(aes(x = x, y = y), fill = for_plot$hex)+
facet_wrap(~image, ncol = 10) +
coord_equal()
简化:
rgb2hex <- function(r,g,b) rgb(r, g, b, maxColorValue = 1)
images %>%
group_by(image) %>%
mutate(y = rep(1:256, each = 256),
x = rep(1:256, times = 256),
r = scales::rescale(r),
g = scales::rescale(g),
b = scales::rescale(b),
hex = rgb2hex(r, g, b)) -> for_plot
编辑:DeltaIV要求在评论中剪下较暗的色调,这是一种方法:
n = 0.2
images %>%
group_by(image) %>%
mutate(y = rep(1:256, each = 256),
x = rep(1:256, times = 256),
r = scales::rescale(r) + n,
g = scales::rescale(g) + n,
b = scales::rescale(b) + n,
hex = rgb(r, g, b, maxColorValue = 1 + n)) -> for_plot
ggplot(for_plot) +
geom_raster(aes(x = x, y = y), fill = for_plot$hex)+
facet_wrap(~image, ncol = 10) +
coord_equal()
增加n = 0.5会产生更亮的图像