Search code examples
rplotly

Vertical Line Plot in Plotly Does Not Respect Order


I am struggling to convince plotly to respect the order of points in my vertical line chart.

Data

library(dplyr)
d <- tribble(
  ~value,     ~n,    ~freq,
  "1",        391,  0.0370, 
  "2",        806,  0.0762, 
  "3",       6366,  0.602,  
  "4",         34,  0.00321,
  "5",       2028,  0.192,  
  "(Missing)", 953, 0.0901 
) %>%
  mutate(value = factor(value, value))

Code

In base R it is rather straight forward:

plot(d$n, as.numeric(d$value), type = "l")

Line Chart

However, if I try do the same in plotly the lines seemed to be sorted according to x values:

library(plotly)

plot_ly(d) %>%
 add_lines(
    x = ~ n, 
    y = ~ value
  )

Why is plotly not respecting my order in d?

Line Chart in wrong Order in Plotly


Solution

  • You would need add_paths.

    plot_ly(d) %>%
      add_paths(
        x = ~ n, 
        y = ~ value
      )
    

    The documentation for add_lines reads:

    "# like add_paths(), but ensures points are connected according to x"

    Hence, it connects by n in your case.