title: R Plotly legend ordering with multiple categories
body: <p>I'm having trouble specifying the order of the legend in a plotly R plot. This is similar to <a href="https://community.plotly.com/t/r-legend-order-with-several-categories/33748" rel="nofollow noreferrer">this unresolved post.</a></p>
  <p>These made-up data are grouped by the <code>group</code> variable with two levels, &quot;A&quot; and &quot;B&quot;. There are two aesthetic properties separating these groups:</p>
  <ul>
  <li>&quot;A&quot; is red with a solid line;</li>
  <li>&quot;B&quot; is blue with a dashed line.</li>
  </ul>
  <p>The desired output is a legend with the blue dotted line, corresponding to the &quot;B&quot; group, at the top.</p>
  <pre><code>library(plotly)
  library(dplyr)
  
  set.seed(1)
  
  dat &lt;- tibble(
      year = rep(2010:2019, 2),
      group = factor(rep(c(&quot;A&quot;, &quot;B&quot;), each = 10), levels = c(&quot;B&quot;, &quot;A&quot;)),
      value = c(
          rnorm(10, 10, 2),
          rnorm(10, 14, 2)
      ),
      colour = rep(c(&quot;red&quot;, &quot;blue&quot;), each = 10),
      linetype = factor(rep(c(&quot;solid&quot;, &quot;dot&quot;), each = 10), levels = c(&quot;solid&quot;, &quot;dot&quot;))
  ) 
  </code></pre>
  <p>If we ignore <code>linetype</code> for now, the legend is correct in that it has &quot;B&quot; above &quot;A&quot; (based on the factor levels for <code>group</code> variable).</p>
  <pre><code>dat %&gt;%
      plot_ly(
          type = &quot;scatter&quot;,
          mode = &quot;lines+markers&quot;,
          x = ~ year,
          y = ~ value,
          color = ~ I(colour),
          name = ~ group
      )
  </code></pre>
  <p>However, when we add <code>linetype</code> in, the legend order is reverted to the default (with &quot;A&quot; above &quot;B&quot;):</p>
  <pre><code>dat %&gt;%
      plot_ly(
          type = &quot;scatter&quot;,
          mode = &quot;lines+markers&quot;,
          x = ~ year,
          y = ~ value,
          color = ~ I(colour),
          linetype = ~ I(linetype),
          name = ~ group
      )
  </code></pre>
  <p>Changing the factor levels of <code>linetype</code> doesn't fix the legend, it just breaks the mapping from <code>linetype</code> to the data:</p>
  <pre><code>dat %&gt;%
      mutate(linetype = factor(linetype, levels = c(&quot;dot&quot;, &quot;solid&quot;))) %&gt;%
      plot_ly(
          type = &quot;scatter&quot;,
          mode = &quot;lines+markers&quot;,
          x = ~ year,
          y = ~ value,
          color = ~ I(colour),
          linetype = ~ I(linetype),
          name = ~ group
      )
  </code></pre>
  <ul>
  <li>R version 4.0.3</li>
  <li>plotly version 4.9.2.1</li>
  </ul>
  <p>Thanks for reading and any suggestions.</p>