控制R中ggplotly中点的顺序

Controlling order of points in ggplotly in R

考虑controlling order of points in ggplot2 in R?中给出的问题(和可重现的例子)。

那里提供的解决方案(首先订购 data.frame,然后是绘图)也适用于我。但是,当我想使用 plotly::ggplotly() 查看结果图时,点的顺序又被打乱了。有人知道如何保持绘图图中点的顺序吗?

实际上,我发现即使没有首先更改绘图/数据框,在这个特定示例中 plotly 创建了正确的顺序。

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()

更安全的选择可能是 @Dinre 's answer of your aforementioned question - 首先将数据分离到不同的层。我在答案中使用了建议的快速基本 R 子集,但您也可以使用 split 或 tidyverse 函数进行拆分。

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()

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