【问题标题】:How to set custom color in AddTimeLine如何在 AddTimeLine 中设置自定义颜色
【发布时间】:2021-07-03 12:18:54
【问题描述】:

我正在尝试使用 leaflet 和 leaftime 包创建时间线图。我想在addTimeline中设置自定义颜色来指定每个点到他的组,如下:

library(leaflet)
library(leaftime)
library(geojsonio)

power_d <- data.frame(
  "Latitude" = c(
    33.515556, 38.060556, 47.903056, 49.71, 49.041667, 31.934167,
    54.140586, 54.140586, 48.494444, 48.494444
  ),
  "Longitude" = c(
    129.837222, -77.789444, 7.563056, 8.415278, 9.175, -82.343889,
    13.664422, 13.664422, 17.681944, 17.681944
  ),
  "start" = seq.Date(as.Date("2015-01-01"), by = "day", length.out = 10),
  "end" = seq.Date(as.Date("2015-01-01"), by = "day", length.out = 10) + 1,
color_temp=rep(c("red","blue","green"),len=10)
)

power_geo <- geojsonio::geojson_json(power_d ,lat="Latitude",lon="Longitude")

leaflet() %>%
  addTiles() %>%
  setView(44.0665,23.74667,2) %>%
  addTimeline(data = power_geo,
  timelineOpts = timelineOptions(
      styleOptions = styleOptions(
    radius = 5,     
    color=color_temp,
    fillColor = color_temp,
    fillOpacity = 1
      )
    )
)

不幸的是,我收到以下错误:

lapply(x, f) 中的错误:找不到对象“color_temp”

我也尝试用power_d$color_temp替换color_temp,代码运行没有错误,但点的颜色没有改变。颜色参数在上面的代码中不起作用,为什么?以及如何解决?

【问题讨论】:

  • 看来你不能像这样传递一个颜色向量但是检查addTimeline中的倒数第三个例子但是将相关行更改为color: data.properties.color_temp

标签: r r-leaflet


【解决方案1】:

您似乎无法使用标准 styleOptions 传递颜色向量,但是,?addTimeline 帮助页面中的示例显示了如何使用一点 JavaScript 根据数据添加颜色(幸运的是,示例中提供了)。

使用以“# 根据数据对每个点设置不同样式”开头的示例,您需要稍微更改它以指向您的颜色矢量,例如将data.properties.color 更改为data.properties.color_temp。运行下面的代码会导致

# code
leaflet(power_geo) %>%
  addTiles() %>%
  setView(44.0665,23.74667,2) %>%
  addTimeline(
    timelineOpts = timelineOptions(
      styleOptions = NULL, 
      pointToLayer = htmlwidgets::JS(
"
function(data, latlng) {
  return L.circleMarker(
    latlng,
    {
      radius: 25,
      color: data.properties.color_temp,
      fillColor: data.properties.color_temp,
      fillOpacity: 1
    }
  );
}
"
      )
    )
  )

【讨论】:

  • 有效!在这种情况下如何设置弹出窗口?我认为它应该通过'L.circleMarker'?例如如果我们想传递 color_temp 和更多信息怎么做?
  • 我找到了! '.bindPopup()' 可以通过popup!
  • 我想在上面的代码中自定义日期。怎么做?我试试stackoverflow.com/questions/68242487/…
  • 为什么在代码中,当我们按下前进(或后退)按钮时,我们有当前时间点和下一个时间点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多