R Plotly - Cannot Order or Organize by a Variable

Viewed 39

I am trying to create a Plotly plot in R, and I cannot seem to get it to break the data down by the "class" variable.

This data is built into R, so it should be easy for anyone to look at.

First, here is the code (I added quotation marks around "class" in a few spots, because the code will not run otherwise):

library(plotly)
library(tidyverse)

mpg %>%
  group_by(model) %>%
  summarise(c = mean(cty), h = mean(hwy), class = class) %>%
  mutate(model = forcats::fct_reorder(model, c), class = forcats::fct_reorder(class, c)) %>%
  plot_ly() %>%
  add_segments(
    x = ~c, y = ~forcats::fct_reorder(model, c),
    xend = ~h, yend = ~model, 
    color = "class", showlegend = TRUE
  ) %>%
  add_markers(
    x = ~c, y = ~model,
    marker = list(symbol = "square",
    color = "class"),
    name = "",
    showlegend = FALSE
  ) %>%
  add_markers(
    x = ~h, y = ~model, 
    marker = list(symbol = "diamond",
                  color = "class"),
    name  = "",
    showlegend = FALSE
  ) %>%
  layout(xaxis = list(title = "Miles per gallon"))

I am trying to get the data to be ordered by the new "c" variable overall, but I want to be able to break the data down by the "class" (the type of vehicle). However, as you can see from the code, every car is the same color, so that isn't happening?

I appreciate any help I can get here. I am pretty new to Plotly, so I could definitely be overlooking something simple.

Thank you!

1 Answers

Instead of mapping the string constant "class" on color, map the class column on the color attribute:

library(plotly)
library(tidyverse)

mpg %>%
  group_by(model) %>%
  summarise(c = mean(cty), h = mean(hwy), class = class) %>%
  mutate(model = forcats::fct_reorder(model, c), class = forcats::fct_reorder(class, c)) %>%
  plot_ly() %>%
  add_segments(
    x = ~c, y = ~forcats::fct_reorder(model, c),
    xend = ~h, yend = ~model, 
    color = ~class, showlegend = TRUE
  ) %>%
  add_markers(
    x = ~c, y = ~model, color = ~class,
    marker = list(symbol = "square"),
    name = "",
    showlegend = FALSE
  ) %>%
  add_markers(
    x = ~h, y = ~model, color = ~class,
    marker = list(symbol = "diamond"),
    name  = "",
    showlegend = FALSE
  ) %>%
  layout(xaxis = list(title = "Miles per gallon"))
#> `summarise()` has grouped output by 'model'. You can override using the
#> `.groups` argument.

Related