简体   繁体   English

Plotly R:将颜色和变换与线图结合使用

[英]Plotly R : Using colour and transformation with a line plot

I'm looking to filter by group (flower species) and the year (fake data I made).我希望按组(花种)和年份(我制作的假数据)进行过滤。 However, when i try do this the filtering breaks.但是,当我尝试这样做时,过滤会中断。 This illustrated in the picture below where setosa is picked however there is virgincia data on the plot.下图说明了这一点,其中选择了 setosa,但该图上有 virgincia 数据。 It looks to be caused by using color = .它看起来是由使用color =引起的。 I provided a solution to this problem, however, in my real example my mode = 'lines' .我为这个问题提供了一个解决方案,但是,在我的真实示例中,我的mode = 'lines' Which doesn't let me use this solution.这不允许我使用此解决方案。

For context, my real example is a Duck curve graph.对于上下文,我的真实示例是 Duck 曲线图。 where the category is country and x-axis is hour of the day.其中类别是国家,x 轴是一天中的小时。

Reproducible example:可重现的例子:

set.seed(42)
iris$year <- sample(2009:2011, 150, replace=TRUE) #MAKING FAKE YEAR DATA

p <- iris %>%
  plot_ly(
    type = 'scatter', 
    x = ~Sepal.Length, 
    y = ~Petal.Length,
    color = ~as.factor(year), # GROUPING BY YEAR
    ####### SAMPLE SOLUTION ######## comment out color =. and uncomment the below
    # marker = list(color = ~as.factor(year), size = 8, opacity = 0.8),
    text = ~Species, # ADDED THIS TO ILLUSTRATE THERE IS WRONG DATA IN THE TRANSFORMATION
    mode = 'markers', # IN MY REAL EXAMPLE IM USING LINES. 
    transforms = list(
      list(
        type = 'filter',
        target = ~Species,
        operation = '=',
        value = unique(iris$Species)[1]
      )
  )) %>% layout(
    updatemenus = list(
      list(
        type = 'dropdown',
        active = 0,
        buttons = list(
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[1]),
               label = unique(iris$Species)[1]),
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[2]),
               label = unique(iris$Species)[2]),
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[3]),
               label = unique(iris$Species)[3])
        )
      )
    )
  )

p

在此处输入图片说明

expected solution: mode = 'lines' & color by year while keeping the filtering of species.预期解决方案: mode = 'lines' & color by year 同时保持物种过滤。 :) :)

Seems odd, but if you reorder your data.frame by your color variable first, your code works fine.看起来很奇怪,但是如果您首先按颜色变量对 data.frame 重新排序,则您的代码可以正常工作。

set.seed(42)
iris$year <- sample(2009:2011, 150, replace=TRUE) #MAKING FAKE YEAR DATA
iris <- iris[order(iris$year), ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM