我正在尝试使用以下代码绘制矢量场,其中一些矢量设置为不可见:
library(cowplot)
size <- 1/12
strength <- 8
centerx <- 0
centery <- -12
diagsize <- 200
x <- rep(1:diagsize - diagsize/2, times = diagsize)
y <- rep(1:diagsize - diagsize/2, each = diagsize)
xend <- numeric()
yend <- numeric()
distance <- numeric()
replace_factor_01 <- numeric()
replace_factor <- numeric()
h <- numeric()
for (i in 1:(diagsize*diagsize)){ #
distance[i] <- sqrt((x[i]-centerx)^2+(y[i]-centery)^2) # simply get absolute distance of each pixel to lens center
replace_factor_01[i] <- 0 # this will be color intensity
replace_factor[i] <- 0 # wheras this will be arrow length
h[i] <- 0 # this will be color (0 = red, 0.667 = blue)
if (distance[i] < 2*3.141592/size){replace_factor_01[i] <- sin(distance[i]*size)} # if within range, compute distortion as value -1..1
replace_factor[i] <- replace_factor_01[i]*strength # linearly stretch
if (replace_factor[i] < 0){h[i] <- 0.667} # set color
xend[i] <- x[i] + (x[i]-centerx)/distance[i]*replace_factor[i] # compute distortion vector
yend[i] <- y[i] + (y[i]-centery)/distance[i]*replace_factor[i]
if ((x[i] %% 5) !=0 | (y[i] %% 5) != 0) {replace_factor_01[i] <- 0} # only set some arrows visible
}
data <- data.frame(x,y,distance, h, replace_factor_01,replace_factor,xend,yend)
p <- ggplot(data,aes(x,y))+
geom_segment(aes(xend=xend,yend=yend),col=hsv(h,abs(replace_factor_01),1))
#geom_segment(aes(xend=xend,yend=yend),col=hsv(h,abs(replace_factor_01),1), size=5)
print(p)
结果如下:
当我使用“size = 5”时,线条不仅会变得更粗,而且看起来像这样:
我出错了什么?
答案 0 :(得分:3)
你的问题是你实际上没有让任何片段“隐形”,你将它们设置为白色。 hsv(x,0,1)
总是= #FFFFFF(白色)
如果我们查看饱和度固定为1的图表,我们可以看到问题。大量的片段被涂成白色,使它们与蓝色和红色片段重叠。当你增加size
时,你就会加剧这个问题。
p <- ggplot(data,aes(x,y))+
geom_segment(aes(xend=xend,yend=yend),col=hsv(h,1,1))
我认为你真正想做的是绘制replace_factor_01
所在的所有段!= 0.所以我们使用data.table
对数据进行子集化:
require(data.table)
setDT(data)
p <- ggplot(data[replace_factor_01 != 0],aes(x,y,color=distance))+
geom_segment(aes(xend=xend,yend=yend),size=3)
与您的颜色匹配的最终版本 - 我将replace_factor_01
映射为颜色(如果您将h
转换为因子,您可以使用scale_color_manual()
获取您定义的两种离散颜色在你的情节中):
p <- ggplot(data[replace_factor_01 != 0],aes(x,y))+
geom_segment(aes(xend=xend,yend=yend,color=replace_factor_01),size=2)+
scale_color_gradient(high="red",low="blue")+
theme(legend.position="none")