Select 使用 ggplotly 指向图表时的数据和名称

Select data and name when pointing it chart with ggplotly

我在 ggplot 中做了所有事情,一切都运行良好。现在我需要它在指向数据点时显示数据。在此示例中,模型(用于识别点)以及 disp 和 wt(轴中的数据)。 为此,我添加了形状(相同的形状,我实际上并不想要不同的形状)来建模数据。并要求 ggplot 不要在图例中显示形状。然后我转换为情节。当我指向圆圈时,我成功地显示了数据,但现在我在显示用逗号分隔的颜色和形状的图例时遇到了问题...

我不想在 plotly 中从头开始重新制作它,因为我没有 plotly 方面的经验,这是一个更大的闪亮项目的一部分,其中图表自动调整轴缩放并添加趋势线图表等我不知道如何在 plotly 中做的事情(为了简单起见我没有包括)。

非常感谢。这几天我已经尝试了一百万种方法,但没有成功。

# choose mtcars data and add rowname as column  as I want to link it to shapes in ggplot
data1 <- mtcars
data1$model <- rownames(mtcars)
# I turn cyl data to character as when charting it showed (Error: Continuous value supplied to discrete scale)
data1$cyl <- as.character(data1$cyl)

# linking colors with cylinders and shapes with models
ccolor <- c("#E57373","purple","green")
cylin <- c(6,4,8)  
# I actually do not want shapes to be different, only want to show data of model when I point the data point. 
models <- data1$model
sshapes <- rep(16,length(models)) 


# I am going to chart, do not want legend to show shape
graff <- ggplot(data1,aes(x=disp, y=wt,shape=model,col=cyl)) + 
  geom_point(size = 1) +
  ylab ("eje y") + xlab('eje x') +
  scale_color_manual(values= ccolor, breaks= cylin)+
  scale_shape_manual(values = sshapes, breaks = models)+
  guides(shape='none') # do not want shapes to show in legend

graff

chart is fine, but when converting to ggplotly, I am having trouble with the legend

# chart is fine, but when converting to ggplotly, I am having trouble with the legend

graffPP <- ggplotly(graff)
graffPP

legend is not the same as it was in ggplot

当我在图表中指向一个数据点时,我成功地显示了轴上的模型和数据...但现在我遇到了图例问题....

据我所知,没有简单的 out-of-the 框解决方案来实现您想要的结果。

使用纯 plotly,您可以通过分配 legendgroups 来实现您的结果,而使用 ggplotly 则 TBMK 不可用。但是,您可以通过操作 ggplotly.

返回的 plotly 对象来手动分配图例组

根据您的情况调整我在 post 上的回答,您可以像这样实现您想要的结果:

library(plotly)

p <- ggplot(data1, aes(x = disp, y = wt, shape = model, col = cyl)) +
  geom_point(size = 1) +
  ylab("eje y") +
  xlab("eje x") +
  scale_color_manual(values = ccolor, breaks = cylin) +
  scale_shape_manual(values = sshapes, breaks = models) +
  guides(shape = "none")

gp <- ggplotly(p = p)

# Get the names of the legend entries
df <- data.frame(id = seq_along(gp$x$data), legend_entries = unlist(lapply(gp$x$data, `[[`, "name")))

# Extract the group identifier, i.e. the number of cylinders from the legend entries
df$legend_group <- gsub("^\((\d+).*?\)", "\1", df$legend_entries)

# Add an indicator for the first entry per group
df$is_first <- !duplicated(df$legend_group)

for (i in df$id) {
  # Is the layer the first entry of the group?
  is_first <- df$is_first[[i]]
  # Assign the group identifier to the name and legendgroup arguments
  gp$x$data[[i]]$name <- df$legend_group[[i]]
  gp$x$data[[i]]$legendgroup <- gp$x$data[[i]]$name
  # Show the legend only for the first layer of the group 
  if (!is_first) gp$x$data[[i]]$showlegend <- FALSE
}
gp