3

Consider the problem (and the reproducable example) given in controlling order of points in ggplot2 in R?.

The solution provided there (first order the data.frame, then plot) is working also for me. However, when I want to view the resulting plot using plotly::ggplotly() the order of points is messed up again. Anybody an idea how to keep the order of points in the plotly graph?

yasel
  • 433
  • 3
  • 13

1 Answers1

0

Actually, I find that plotly creates the right order in this particular example even without changing the plot/ data frame in a first place.

library(tidyverse)
library(plotly)

set.seed(1)
mydf <- data.frame(x=rnorm(500),  label = 'a', stringsAsFactors = FALSE) %>% mutate(y = rnorm(500)*0.1 + x)
mydf$label[50] <- "point"

ggplot(mydf) + geom_point(aes(x=x, y=y, color=label, size = label)) + 
  scale_size_manual(values = c(a = 0.1,point = 2))

plotly::ggplotly()

enter image description here

The safer option may probably be @Dinre 's answer of your aforementioned question - separate your data to different layers first. I am using the suggested quick base R subset as in the answer, but you can also split using split or with tidyverse functions.

df_layer_1 <- mydf[mydf$label=="a",]
df_layer_2 <- mydf[mydf$label=="point",]

ggplot() + 
  geom_point(data=df_layer_1, mapping = aes(x, y), colour="orange", size = .1) +
  geom_point(data=df_layer_2, aes(x, y), colour="blue", size = 2)

plotly::ggplotly()

enter image description here

R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

other attached packages:
[1] plotly_4.9.0  ggplot2_3.2.0
tjebo
  • 21,977
  • 7
  • 58
  • 94