我正在尝试(但失败)在
prop
列中绘制各个数据点,作为plotly
3D螺旋中的完整圆圈(从上面看时)(参见下面的数据)。我的想法是
rep
将 prop
值吃掉 10,以便有足够的点来绘制圆圈,但结果图与我想要的效果相去甚远 - 一个 3D 螺旋,其中每个 prop
由
size
和
position
分组的值表示为完整的圆圈。怎么才能实现呢?
data <- df %>%
group_by(size) %>%
slice(rep(row_number(), 10)) %>%
arrange(size, position) %>%
group_by(size, position) %>%
mutate(
radius = prop,
theta = 2 * pi * position/row_number(),
x = radius * sin(theta),
y = radius * cos(theta)
) %>%
ungroup() %>%
mutate(z = row_number())
library(plotly)
plot_ly(data, x = ~x, y = ~y, z = ~z,
type = 'scatter3d',
mode = 'lines',
line = list(width = 5, color = ~size,
colorscale = list(c(0,'#0000FF'), c(0.5, "#00FF00"), c(1,'#FF0000'))))
编辑:
我在这里至少有一个初步的解决方案:
data <- df %>%
group_by(size) %>%
slice(rep(row_number(), 360)) %>% # larger number of duplicated rows
arrange(size, position) %>%
group_by(size, position) %>%
mutate(row = row_number(),
radius = prop,
theta = 2 * pi * position/row,
x = radius * sin(theta),
y = radius * cos(theta)
) %>%
ungroup() %>%
mutate(z = consecutive_id(position)) # different conceptualization of z
结果更接近我的想法:
仍然不理想的是(i)连接不同
z
级别的线和(ii)圆形平面上的(奇怪的)连接线。 如何将这些类型的线条删除、使其不可见或更改为虚线?
数据:
df <- structure(list(size = c(3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
5L, 5L), position = c(1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5), prop = c(0.0926574818826153,
0.110336863900613, 0.30584534522577, 0.0632319256702261, 0.0857179727070362,
0.0963964254605284, 0.269251863083524, 0.0500172581505538, 0.0706956603595971,
0.0864162665913584, 0.102858577300825, 0.288838683360005)), row.names = c(NA,
-12L), class = c("tbl_df", "tbl", "data.frame"))
不确定这是否接近您想要实现的目标,但我可以通过调整此处记录的 spring 的想法来获得 3 个独立的螺旋。
split = ~z
中的
plot_ly()
通话避免了连接线。
library(tidyverse)
library(plotly)
create_spiral <- \(x, y, xend, yend, diameter = 1, tension = 0.75, n = 50) {
length <- sqrt((x - xend)^2 + (y - yend)^2)
n_revolutions <- length / (diameter * tension)
n_points <- n * n_revolutions
radians <- seq(0, n_revolutions * 2 * pi, length.out = n_points)
x <- seq(x, xend, length.out = n_points)
y <- seq(y, yend, length.out = n_points)
data.frame(
x = cos(radians) * diameter / 2 + x,
y = sin(radians) * diameter / 2 + y
)
}
spirals <- map(1:3, \(z) {
create_spiral(
x = 4, y = 2, xend = 8, yend = 6,
diameter = 4, tension = 0.6, n = 50
) |>
mutate(z = z * 5)
}) |>
bind_rows()
plot_ly(spirals,
x = ~x, y = ~y, z = ~z, split = ~z,
type = "scatter3d",
mode = "lines"
)
split
删除圆圈之间的连接线:
remove_rows
[1] 721 722 1441 1801 1802 2161 2162 2163 3241 3242 3601 3602 3603 3961 3962
[16] 3963 3964
data5 <- data4[-remove_rows, ]
plot_ly(data5, x = ~x, y = ~y, z = ~z, split = factor(data5$z),
type = 'scatter3d',
mode = 'lines',
line = list(width = 5, color = ~size,
colorscale = list(c(0,'#0000FF'), c(0.5, "#00FF00"), c(1,'#FF0000'))))
圆圈之间的颜色区别消失了。值得考虑删除的行是否是要删除的“正确”行。删除和随后的
split
会模糊绘图顺序,因为给定
z
上的绘图从前一个
z
的连接线开始。1、2、4、8、9 级无需移除即可达到其独特的形状。它可能更能说明您的“数据”,而不是像上面那样删除初始行,而是通过
z[x][1]
CCW 之后的行被认为是虚假的并被删除。这样做,各个级别的形状会更加相似。