数值向量的不透明度

Opacity by numeric vector

我有一个 very stylized line chart,我想用一个 add_trace 命令绘制我所有的线条,希望这能让我的代码更整洁。

我有两个问题:

  1. 我想要 high 行的低不透明度和 low 行的完全不透明度。如果我尝试它似乎随机分配不透明度。
  2. 我希望上面的线是实线,下面的线是虚线。相反的情况发生了。

关于这些问题我有两个问题:

  1. plotly 的这种 'strange'(不合逻辑)行为可以修复吗?也许通过使用一些 layout 选项?
  2. 出现这种 'strange' 行为是因为我在路径的尾部吗?

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"))

这对你有用吗?

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"))