我有一个名为plt.total
的数据框,它由5行(ob)和7列(变量)组成,如下所示:
set.seed(2018)
plt.total <- data.frame(replicate(7,runif(5, min=0.80, max=0.9)))
colnames(plt.total) <- c("R", paste0("Matrix",1:6))
plt.total[,1] <- c(1:5)
然后我使用plotly
对其进行绘制,如下所示:
plot_ly(data=plt.total, x = ~R, y = ~Matrix1, name = 'Matrix 1', type = 'scatter', mode = 'lines',
line = list(color = 'rgb(205, 12, 24)', width = 3, dash = 'dashdot')) %>%
add_trace(y = ~Matrix2, name = 'Matrix 2', line = list(color = 'rgb(22, 96, 167)', width = 3, dash = 'solid' )) %>%
add_trace(y = ~Matrix3, name = 'Matrix 3', line = list(color = 'rgb(205, 12, 24)', width = 3, dash = 'longdashdot')) %>%
add_trace(y = ~Matrix4, name = 'Matrix 4', line = list(color = 'rgb(22, 96, 167)', width = 3, dash = 'dash')) %>%
add_trace(y = ~Matrix5, name = 'Matrix 5', line = list(color = 'rgb(205, 12, 24)', width = 3, dash = 'dot')) %>%
add_trace(y = ~Matrix6, name = 'Matrix 6', line = list(color = 'rgb(22, 96, 167)', width = 3, dash = 'dot')) %>%
layout(title = "", legend = list(x=0, y=0, font = list(family = "Times", size = 14, color = "#000")))
但是,我的问题是plt.total
会不时更改“列”的数量,因此我试图找到一种避免每次都修改脚本的方法(使用add_trace
) 。因此,我的目标是使用plotly
绘制数据帧每一列的输入,而与列数无关。
谢谢
答案 0 :(得分:2)
一种方法是将plt.total
表转换为长而整洁的格式,以便您可以映射到矩阵号,而不必手动添加单独的序列。
在这里,我们将数据的形状更改为较长的形状,并使用新的“矩阵”字段来表示观测值属于哪个系列。
plt.total.tidy <-
plt.total %>%
tidyr::gather(matrix, value, -R)
我的plotly-fu还不是很好,所以这里我先在ggplot中制作图表,然后使用plotly::ggplotly
将其移植到plotly中,并添加您所做的布局选择。如果您想手动指定颜色和线型,而不是为它们指定颜色和线型,则可以使用scale_color_manual
和scale_linetype_manual
函数来实现。
library(ggplot2)
p <- ggplot(plt.total.tidy, aes(R, value, color = matrix, lty = matrix)) +
geom_line(size = 1.1) +
theme(legend.position = c(0.1,0.1)) #+
# Could add below lines if you want to manually pick colors and linetypes
# scale_color_manual(....) +
# scale_linetype_manual(....) +
ggplotly(p) %>%
layout(title = "", legend = list(x=0, y=0, font = list(family = "Times", size = 14, color = "#000")))
答案 1 :(得分:2)
我设法使用列表而不是数据框,如下所示。 也许有人知道更好的方法?
set.seed(2018)
plt.total <- list()
n <- 10 # number of lines in the plot
for (i in 1:n) {
plt.total[i] <- list(
list(x=c(1:5), y=replicate(1,runif(5, min=0.80, max=0.9)), color=randomcoloR::randomColor(n, luminosity="light")))
}
p <- plot_ly()
p
for(i in 1:length(plt.total)) { p <- add_trace(p, y=plt.total[[i]]$y,
x=plt.total[[i]]$x, line=list(color=plt.total[[i]]$color),
name=paste0("Matrix",i), mode = "lines")%>%
layout(title = "", legend = list(x=0, y=0,
font = list(family = "Times",
size = 14, color = "#000")),
xaxis = list(title = "R Value", showline = TRUE,
annotations= x, range=c(1, 5), linewidth = 2, mirror = "ticks",
titlefont = list(family = "Times", size = 18, color = "#000"),
tickfont = list(family = "Times", size = 14, color = "#000")),
yaxis = list (title = "Value", showline = TRUE,
linewidth = 2,mirror = "ticks",
titlefont = list(family = "Times", size = 18, color = "#000"),
tickfont = list(family = "Times", size = 14, color = "#000")) )
}
p