[英]How to connect pairs of data points in plotly in R
library(plotly)
data <- data.frame(name = c("Ana", "Ana", "Joyce", "Joyce", "Kam", "Kam"),
type = c("A", "B", "A", "B", "A", "B"),
score1 = c(100, 90, 0, 20, 33, 99),
score2 = c(100, 30, 0, 20, 55, 66))
> data
name type score1 score2
1 Ana A 100 100
2 Ana B 90 30
3 Joyce A 0 0
4 Joyce B 20 20
5 Kam A 33 55
6 Kam B 99 66
我有一个数据集,其中每个人都有 2 个测试type A
分数和 2 个测试type B
的分数。 我想用虚线连接每个人的考试成绩。
这是我的 plot 代码,没有虚线:
> plot_ly(data = data,
x = ~score1,
y = ~score2,
hoverinfo = 'text',
text = ~I(name),
mode = "markers",
transforms = list(
list(
type = 'groupby',
groups = data$type,
styles = list(
list(target = "A", value = list(marker =list(color = 'red'))),
list(target = "B", value = list(marker =list(color = 'blue')))
)
)
))
所需的 output 是这样的:
由于您在点 plot 中指定了特定的 colors,因此首先创建线条会更容易。
首先,对于每条线段,您需要一条单独的轨迹。 只有三个,但由于其动态特性,我使用了这种方法。 您的线段由name
中的数据连接,所以我用它来控制线迹创建。
plt <- plot_ly()
lapply(1:length(unique(df1$name)),
function(j) {
df2 <- filter(df1, name == unique(df1$name)[j])
plt <<- plt %>%
add_trace(type = "scatter", mode = "lines", data = df2,
x = ~score1, y = ~score2, showlegend = F, hoverinfo = "none",
line = list(color = "black", dash = "dash"))
})
现在所有行都记录在plt
中,让我们将原始散点数据添加到 plot。我添加了hovertemplate
,以便 hover 内容不包含跟踪名称。
plt %>%
add_trace(data = df1, x = ~score1, y = ~score2, hovertext = ~name,
color = ~type, mode = "markers", showlegend = T,
hovertemplate = "%{hovertext}<extra></extra>",
marker = list(color = ifelse(df1$type == "A", "red", "blue")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.