【问题标题】:Shiny R - Custom markers depending on conditionShiny R - 根据条件自定义标记
【发布时间】:2018-05-04 19:46:41
【问题描述】:

我想知道是否可以在 makeIcon() 函数中添加条件

我有一张桌子:

id ; lat ; long ; class1 ; class2 ; class3

我希望图标根据这些条件有所不同:

if class1 == A, I want image1 
else, if class2 == B, I want image2
else, if class3 == C, I want image 3
else, I want image4

【问题讨论】:

    标签: r shiny leaflet


    【解决方案1】:

    makeIcon() 内,可能不会。来自 API 文档:

    对于将单个图标应用于一组标记的简单情况,请使用 制作图标()。 (link)

    您可能想要使用 icon(),它是一个图标向量,可用于为不同的数据绘制不同的图标:

    如果您有几个图标要应用,它们的差异只有几个 参数(即它们共享相同的大小和锚点,但具有 不同的 URL),使用 icons() 函数。

    Icons 包含一个带有每个图标图像 url 的向量(或任何其他在数据中不同的图标属性)。

    要执行逻辑,最简单的方法是在 icon 函数中嵌套两个额外的 ifelse 语句,例如:

      iconUrl = ifelse(df$class1  == "a", "image1",
         ifelse(df$class2 == "c", "image2",
            ifelse(df$class3 =="x", "image3", 
               "some other url" #the else condition
                        )
                )
      ),
    

    这是一个最小的示例,它只是对链接到 api 文档中示例的轻微补充:

    library(leaflet)
    
    lat<- c(57,65,60,61)
    long<-c(-130,-125,-140,-135)
    class1<-c("a","b","c","d")
    class2<-c("b","c","d","e")
    class3<-c("b","c","d","f")
    
    
    df <- data.frame(lat,long,class1,class2,class3,stringsAsFactors=FALSE)
    
    leafIcons <- icons(
      iconUrl = ifelse(df$class1  == "a", "http://leafletjs.com/examples/custom-icons/leaf-green.png",
        ifelse(df$class2 == "c", "http://leafletjs.com/examples/custom-icons/leaf-red.png",
          ifelse(df$class3 == "d", "http://leafletjs.com/examples/custom-icons/leaf-orange.png",
                 "http://leafletjs.com/docs/images/logo.png"
                 )            
         )
      ),      
      iconWidth = 38, iconHeight = 95,
      iconAnchorX = 22, iconAnchorY = 94,
      shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
      shadowWidth = 50, shadowHeight = 64,
      shadowAnchorX = 4, shadowAnchorY = 62
    )
    
    leaflet(data = df) %>% addTiles() %>%
      addMarkers(~long, ~lat, icon = leafIcons)
    

    抱歉,这里的图片选择不是很棒。如果您希望其他一些属性根据每个图标的数据而有所不同,例如图标大小,您可以在 iconWidth 和/或 iconHeight 上使用相同的过程:

      iconHeight = ifelse(df$class1  == "a", 100,
        ifelse(df$class2 == "c", 200,
          ifelse(df$class3 == "d", 300,
                 400
            )            
         )
      ),
    

    【讨论】:

    • 非常感谢!我还有一个问题。这可以使用计算机上的图像而不是 url 吗?
    • 好的,我找到了答案。再次感谢安德鲁。
    猜你喜欢
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多