Skip to content

Commit 7c7dfee

Browse files
committedNov 13, 2023
3 way color gradient
1 parent cd04367 commit 7c7dfee

File tree

3 files changed

+61
-1
lines changed

3 files changed

+61
-1
lines changed
 

‎.DS_Store

-2 KB
Binary file not shown.
+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
https://stackoverflow.com/questions/11777124/three-way-color-gradient-fill-in-r
2+
3+
#works well, but slow
4+
5+
plot(NA,NA,xlim=c(0,1),ylim=c(0,1),asp=1,bty="n",axes=F,xlab="",ylab="")
6+
segments(0,0,0.5,sqrt(3)/2)
7+
segments(0.5,sqrt(3)/2,1,0)
8+
segments(1,0,0,0)
9+
# sm - how smooth the plot is. Higher values will plot very slowly
10+
sm <- 500
11+
for (y in 1:(sm*sqrt(3)/2)/sm){
12+
for (x in (y*sm/sqrt(3)):(sm-y*sm/sqrt(3))/sm){
13+
## distance from base line:
14+
d.red = y
15+
## distance from line y = sqrt(3) * x:
16+
d.green = abs(sqrt(3) * x - y) / sqrt(3 + 1)
17+
## distance from line y = - sqrt(3) * x + sqrt(3):
18+
d.blue = abs(- sqrt(3) * x - y + sqrt(3)) / sqrt(3 + 1)
19+
points(x, y, col=rgb(1-d.red,1 - d.green,1 - d.blue), pch=19)
20+
}
21+
}
22+
23+
# works well and fast
24+
plot(NA,NA,xlim=c(0,1),ylim=c(0,1),asp=1,bty="n",axes=F,xlab="",ylab="")
25+
sm <- 500
26+
x <- do.call(c, sapply(1:(sm*sqrt(3)/2)/sm,
27+
function(i) (i*sm/sqrt(3)):(sm-i*sm/sqrt(3))/sm))
28+
y <- do.call(c, sapply(1:(sm*sqrt(3)/2)/sm,
29+
function(i) rep(i, length((i*sm/sqrt(3)):(sm-i*sm/sqrt(3))))))
30+
d.red = y
31+
d.green = abs(sqrt(3) * x - y) / sqrt(3 + 1)
32+
d.blue = abs(- sqrt(3) * x - y + sqrt(3)) / sqrt(3 + 1)
33+
points(x, y, col=rgb(1-d.red,1 - d.green,1 - d.blue), pch=19)
34+
35+
36+
# Coordinates of the triangle
37+
tri <- rbind(sin(0:2*2/3*pi), cos(0:2*2/3*pi))
38+
39+
# Function for calculating the color of a set of points `pt`
40+
# in relation to the triangle
41+
tricol <- function(pt, sharpness=2){
42+
require(splancs)
43+
RGB <- sapply(1:3, function(i){
44+
a <- sweep(pt, 2, tri[,i])
45+
b <- apply(tri[,-i], 1, mean) - tri[,i]
46+
sharpness*((a %*% b) / sum(b^2))-sharpness+1
47+
})
48+
RGB[-inpip(pt,t(tri)),] <- 1 # Color points outside the triangle white
49+
do.call(rgb, unname(as.data.frame(pmin(pmax(RGB, 0), 1))))
50+
}
51+
52+
# Plot
53+
res <- 1000 # Resolution
54+
xi <- seq(-1, 1, length=res) # Axis points
55+
yi <- seq(-.8, 1.2, length=res)
56+
x <- xi[1] + cumsum(diff(xi)) # Midpoints between axis points
57+
y <- yi[1] + cumsum(diff(yi))
58+
xy <- matrix(1:(length(x)*length(y)), length(x))
59+
image(xi, yi, xy, col=tricol(as.matrix(expand.grid(x,y))), useRaster=TRUE)
60+
lines(tri[1,c(1:3,1)], tri[2,c(1:3,1)], type="l")
61+

‎3way_color_gradient

-1
This file was deleted.

0 commit comments

Comments
 (0)
Please sign in to comment.