这次我想使用R和ggplot2来产生一些简单的数学结,并根据三重着色进行着色.
这是我的代码
library (ggplot2)
theme_set(theme_bw())
phi = seq(2*pi, length = 1000)
x = sin(phi)+2*sin(2*phi)
y = cos(phi)-2*cos(2*phi)
z = -sin(3*phi)
diff <- abs(x - y)
mindiff <- sort(diff)[1:3] #knot-specific number of intersections
dindice <- which(diff %in% mindiff)
dcol <- c(rep(1,(length(0:dindice[1]))-1), rep(2,(length(dindice[1]:dindice[2]))-1), rep(3,(length(dindice[2]:dindice[3])-1)), rep(1,(length(dindice[3]:length(diff)))-1))
ggknot <- data.frame(x,y,z, dcol)
knot <- ggplot(ggknot, aes(x, y)) + geom_point(aes(colour = as.factor(dcol)))
如您所见,x和y是用于生成结的正弦和余弦分量的函数,phi是均匀间隔线性值的向量.我的想法是通过计算它们的差异找到最接近x,y平面的点,并找到用于ggplot的索引和分组的前三个最小值(dcol).但结果如下:
颜色是不规则交替的,它们应该像this.灵感来自于真棒glowing python blog,所以也欢迎python的解决方案.有任何想法吗?
解决方法:
看起来phi = seq(2 * pi,length = 1000)从2 * pi到1000生成994个点.将此与先前在交叉点上的观察相结合表明这是正确的方法:
phi = seq(0, 2 * pi, length = 1200) - .27
x = sin(phi)+2*sin(2*phi)
y = cos(phi)-2*cos(2*phi)
z = -sin(3*phi)
dcol <- c(rep(1, 400), rep(2, 400), rep(3, 400))
ggknot <- data.frame(x,y,z, dcol)
knot <- ggplot(ggknot, aes(x, y)) + geom_point(aes(colour = as.factor(dcol)))
对于方程的(x,y)交点,代数地发现“幻数”0.27.选择dcol是因为颜色应该是均匀间隔的(通过对称).