手动设置图例名称

Manually set the legend names

我有一个数据框,我在下面进行了正确处理,以便创建一个聚类散点图:

library(tidyverse)  # data manipulation
library(cluster)    # clustering algorithms
library(factoextra) # clustering algorithms & visualization
library(plotly)
df <- USArrests
df <- na.omit(df)

df <- scale(df)
distance <- get_dist(df)

k2 <- kmeans(df, centers = 2, nstart = 25)
df %>%
  as_tibble() %>%
  mutate(cluster = k2$cluster,
         state = row.names(USArrests))
p2<-fviz_cluster(k2, data = df, geom="point")
#+ scale_fill_discrete(name = "Cluster", labels = c("1", "2", "3","4"))
p2
ggplotly(p2)

当我使用 ggplotly() 时,图例名称会发生​​变化,所以我正在寻找一种方法来手动设置它们,甚至完全隐藏图例。

我遇到的最简单方法是重命名对象内的标签。

p2<-fviz_cluster(k2, data = df, geom="point")

p3 <- ggplotly(p2)

p3[["x"]][["data"]][[2]][["name"]] <- "2"
p3

它不是很漂亮,但在短期内有帮助。

编辑:所以有不止一个问题 第一:关于图例标签 第二:关于剧情中的互动点 # 给出了大部分示例代码, # 只改变中心变量

# Example
library(tidyverse)  # data manipulation
library(cluster)    # clustering algorithms
library(factoextra) # clustering algorithms & visualization
library(plotly)
df <- USArrests
df <- na.omit(df)

df <- scale(df)
distance <- get_dist(df)

# added center variable for number of centers in kmeans
# this will also be used to select elemnets from ggplot or ggplotly later

centers=4
k2 <- kmeans(df, centers = centers, nstart = 25)
df %>%
  as_tibble() %>%
  mutate(cluster = k2$cluster,
         state = row.names(USArrests))

p2<-fviz_cluster(k2, data = df, geom="point")

p2
p3 <- ggplotly(p2)

# Solution
# First Problem: Changing legend labels 
# Because the transition from ggplot to ggplotly
#   messes up multiple scales like here (color and shape)
# Why it looks like intended when only changing the point layer, 
#   I don't know

for (i in 1:centers) {
  p3[["x"]][["data"]][[i]][["name"]] <- i
}

# Second Problem: interactive points
# ggplot saves the data in one list and ggplotly splits the data 
#    depending on layer and cluster
# for the labels it is enough to change the point layers 
#    (the first x depending on num. of centers)
# to add more inforamtion to labels 
#   manipulate the variable names_states with html
for (i in 1:centers) {
  name_states <- p2[["data"]]%>%
    filter(cluster==i)%>%
    select(name)

  p3[["x"]][["data"]][[i]][["text"]] <- as.vector(name_states$name)
}

# Changing order of layers because polygon-layer is on top and 
#    makes it impossible to hover over points beneeth
p3[["x"]][["data"]] <- p3[["x"]][["data"]][(centers*3):1]

# Now you can hover over every point and can see the state name
p3