当数据只有一个类别时显示颜色图例

Display color legend when data has only one category

我刚刚发现,如果一个变量映射到plotly中的color参数,只有当变量有多个类别时才会自动显示图例。如下图所示。 df1 有两个类别,它们显示在图例中。另一方面,df2 只有一个类别,没有显示图例。我的目标是在 df2 图中显示图例。

library(plotly)

df1 <- data.frame(
  x = 1:100,
  y = rnorm(100),
  category = sample(c("cat", "dog"), 100, replace = TRUE)
)

plot_ly(
  type = "scatter",
  mode = "markers",
  data = df1,
  x = ~x,
  y = ~y,
  color = ~category
)

f2 <- data.frame(
   x = 1:100,
   y = rnorm(100),
   category = "dog"
)

plot_ly(
  type = "scatter",
  mode = "markers",
  data = df2,
  x = ~x,
  y = ~y,
  color = ~category
)

您可以使用参数 showlegend:

添加图例
plot_ly(
  type = "scatter",
  mode = "markers",
  data = df2,
  x = ~x,
  y = ~y,
  color = ~category
) %>% layout(showlegend = TRUE)