我有一堆来自同一主题的研究的“配对”观察结果,我正在尝试构建一个意大利面条图来可视化这些观察结果,如下所示:
library(plotly)
df <- data.frame(id = rep(1:10, 2),
type = c(rep('a', 10), rep('b', 10)),
state = rep(c(0, 1), 10),
values = c(rnorm(10, 2, 0.5), rnorm(10, -2, 0.5)))
df <- df[order(df$id), ]
plot_ly(df, x = type, y = values, group = id, type = 'line') %>%
layout(showlegend = FALSE)
Run Code Online (Sandbox Code Playgroud)
它产生了我正在寻找的正确情节。但是,代码以自己的颜色显示了每个分组的行,这真的很烦人,让人分心。我似乎无法找到摆脱颜色的方法。
额外问题:我实际上想使用color = state该变量并实际为斜线着色。
任何方法/想法?
您可以像这样将线条设置为相同的颜色
plot_ly(df, x = type, y = values, group = id, type = 'scatter', mode = 'lines+markers',
line=list(color='#000000'), showlegend = FALSE)
Run Code Online (Sandbox Code Playgroud)
对于“奖金”二合一问题“如何通过与用于分组的变量不同的变量进行着色”:
如果您只绘制标记而不绘制线条,这将很简单,因为您可以简单地向marker.color. 然而不幸的是,line.color它只需要一个值,而不是一个向量,所以我们需要解决这个限制。
如果数据不是太多(在这种情况下,这种方法会变慢,下面给出了一种更快的方法),您可以通过将它们作为单独的轨迹在循环中逐个添加(循环 id)来单独设置每条线的颜色
p <- plot_ly()
for (id in df$id) {
col <- c('#AA0000','#0000AA')[df[which(df$id==id),3][1]+1] # calculate color for this line based on the 3rd column of df (df$state).
p <- add_trace(data=df[which(df$id==id),], x=type, y=values, type='scatter', mode='markers+lines',
marker=list(color=col),
line=list(color=col),
showlegend = FALSE,
evaluate=T)
}
p
Run Code Online (Sandbox Code Playgroud)
尽管这种每行一条轨迹的方法在概念上可能是最简单的方法,但如果应用于数百或数千个线段,它确实会变得非常(不切实际)缓慢。在这种情况下,有一种更快的方法,即每种颜色只绘制一条线,但通过NA在单独的线段之间插入's 并使用connectgaps=FALSE选项将线分成缺失的线段,将该线分成多个线段数据。
首先使用dplyr在行段之间插入缺失值(即,对于每个唯一值,id我们NA在提供x和y坐标的列中添加一行)。
library(dplyr)
df %<>% distinct(id) %>%
`[<-`(,c(2,4),NA) %>%
rbind(df) %>%
arrange (id)
Run Code Online (Sandbox Code Playgroud)
和情节,使用connectgaps=FALSE:
plot_ly(df, x = type, y = values, group = state, type = 'scatter', mode = 'lines+markers',
showlegend = FALSE,
connectgaps=FALSE)
Run Code Online (Sandbox Code Playgroud)