使用plotly绘制线图时定义配色方案 [英] define color scheme when plotting line plot with plotly

查看:262
本文介绍了使用plotly绘制线图时定义配色方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据表(它并不总是相同,并且列数总是不同)和用于绘制折线图的代码:

I have the following data table (which is not always the same, and has always a different number of columns) and code for plotting a line chart:

dt <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                 Germany = rnorm(365, 2, 1), Austria = rnorm(365, 3, 4), 
                 Czechia = rnorm(365, 2, 3), check.names = FALSE)

colNames <- names(dt)[-1]           ## assuming date is the first column
p <- plotly::plot_ly()

for(trace in colNames){
  p <- p %>% plotly::add_trace(data = dt, x = ~date, y = as.formula(paste0("~`", trace, "`")), name = trace,
                               type = 'scatter', mode = 'lines', connectgaps = TRUE, 
                               hovertemplate = paste("%{xaxis.title.text}:  %{x}<br>",
                                                     "%{yaxis.title.text}:  %{y}<br>") )
}

p %>% 
  layout(title = "Coal",
         xaxis = list(title = "Date"),
         yaxis = list (title = "\u20ac/MWh")) 

这将产生以下图:

我想在不同的绿色阴影中创建不同的颜色选择(最暗= #007d3c" #419F44" 和最亮= #81C07A" ).

I would like to create a different color selection in different shades of green (darkest = "#007d3c", "#419F44" and lightest = "#81C07A").

我该怎么做?

推荐答案

也许尝试

colNames <- names(dt)[-1] ## assuming date is the first column
colors <- setNames(c("#007d3c", "#419F44", "#81C07A"), colNames)
line_type <- setNames(c("solid", "dot", "dash"), colNames)
p <- plotly::plot_ly()

for(trace in colNames){
  p <- 
    p %>% 
    plotly::add_trace(
      data = dt, x = ~date, y = as.formula(paste0("~`", trace, "`")), name = trace,
      type = 'scatter', mode = 'lines', connectgaps = TRUE, 
      hovertemplate = paste("%{xaxis.title.text}:  %{x}<br>",
                            "%{yaxis.title.text}:  %{y}<br>"), 
      line = list(color = colors[[trace]], dash = line_type[[trace]])
    )
}


p %>% 
  layout(
    title = "Coal",
    xaxis = list(title = "Date"),
    yaxis = list (title = "\u20ac/MWh")
  ) 

输出图表看起来像这样

按照@ismirsehregal的帖子更正了line_type向量

这篇关于使用plotly绘制线图时定义配色方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆