我有一个very stylized line chart,我想用一个add_trace
命令来绘制我的所有行,希望这会使我的代码更整洁。
我有两个问题:
high
行的透明度较低,而low
行的透明度最高。如果尝试,似乎是随机分配不透明度。关于这些问题,我有两个问题:
plotly
的这种“奇怪”(非逻辑)行为是否可以解决?也许通过使用一些layout
选项? plotly
示例通常会告诉您为每行或其他对象编写一个新的add_trace
函数。我正在尝试通过一个add_trace
函数来实现我的所有代码行。
在我的真实数据中,我有十多条线可以绘制,如果我可以将一些线绘制在一起,那将真的很有帮助。以下是一些示例图形和数据:
我尝试了以下代码:
month <- c('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December')
high_2000 <- c(32.5, 37.6, 49.9, 53.0, 69.1, 75.4, 76.5, 76.6, 70.7, 60.6, 45.1, 29.3)
low_2000 <- c(13.8, 22.3, 32.5, 37.2, 49.9, 56.1, 57.7, 58.3, 51.2, 42.8, 31.6, 15.9)
high_2007 <- c(36.5, 26.6, 43.6, 52.3, 71.5, 81.4, 80.5, 82.2, 76.0, 67.3, 46.1, 35.0)
low_2007 <- c(23.6, 14.0, 27.0, 36.8, 47.6, 57.7, 58.9, 61.2, 53.3, 48.5, 31.0, 23.6)
high_2014 <- c(28.8, 28.5, 37.0, 56.8, 69.7, 79.7, 78.5, 77.8, 74.1, 62.6, 45.3, 39.9)
low_2014 <- c(12.7, 14.3, 18.6, 35.5, 49.9, 58.0, 60.0, 58.6, 51.7, 45.2, 32.2, 29.1)
data <- data.frame(month, high_2000, low_2000, high_2007, low_2007, high_2014, low_2014)
library(plotly)
df<-tidyr::gather(data,key,values,-month)
plot_ly(data=df,x=~month,y=~values,split=~key,type="scatter",
mode="lines",opacity=ifelse(grepl('high',df$key),0.5,1),line=list(color='#1f77b4'),
linetype=ifelse(grepl('2000',df$key),'solid','dashed')) %>%
layout(xaxis=list(categoryarray = month, categoryorder = "array"))
答案 0 :(得分:2)
这对您有用吗?
df$key <- as.factor(df$key)
df$key <- factor(df$key , levels = c("high_2014","high_2007", "high_2000", "low_2014","low_2007", "low_2000"))
df$high_low <- substr(df$key, 1, 2)
df$high_low <- factor(df$high_low , levels = c("hi","lo"))
df <- df %>% arrange(high_low)
plot_ly(data=df,x=~month,y=~values,split=~key,type="scatter", mode="lines", opacity=ifelse(grepl('high',df$key),0.5,1), line=list(color='#1f77b4'),
linetype= ~ high_low, linetypes = c('solid', 'dashed')) %>%
layout(xaxis=list(categoryarray = month, categoryorder = "array"))