You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly中实现鼠标悬停时geom_point尺寸增大?

实现Plotly散点图鼠标悬停时放大效果

问题描述

我编写了如下代码,实现了带有背景图片(必要需求)和数据点的可视化,请问能否通过操作plotly,使geom_point在鼠标悬停时增大尺寸(例如从当前的5增大到10)?

原代码:

library(plotly)
library(ggplot2)
library(lorem)

df <- data.frame(
  id = 1:50,
  value = rnorm(50)
)

# background image (necessary)
image_destination <- "https://i.imgur.com/ojTcMtN.jpeg"

gg <- ggplot(df,
             aes(x = id,
                 y = value,
                 text = ipsum_words(50, collapse = F) 
             )
) +
  geom_point(color = "red", alpha = 0.5, size = 5) +
  theme_bw()


# create plot
pp <- ggplotly(gg,
               tooltip = c("text"))

# display plot
plotly::layout(pp,
               # tooltip = c("text"),
               images = list(
                 list(
                   source =  image_destination,
                   xref = "x",
                   yref = "y",
                   x = 0,
                   y = 2,
                   sizex = 100,
                   sizey = 4,
                   sizing = "stretch",
                   opacity = 1,
                   layer = "below"
                 )
               ))

解决方案

可以通过Plotly的style()函数配置标记点的悬停状态属性来实现这个效果,同时完全保留原有的背景图片设置。修改后的完整代码如下:

library(plotly)
library(ggplot2)
library(lorem)

df <- data.frame(
  id = 1:50,
  value = rnorm(50)
)

# background image (necessary)
image_destination <- "https://i.imgur.com/ojTcMtN.jpeg"

gg <- ggplot(df,
             aes(x = id,
                 y = value,
                 text = ipsum_words(50, collapse = F) 
             )
) +
  geom_point(color = "red", alpha = 0.5, size = 5) +
  theme_bw()

# 创建plotly对象
pp <- ggplotly(gg, tooltip = c("text"))

# 配置悬停放大效果
pp <- pp %>%
  style(
    marker = list(
      size = 5,          # 默认尺寸
      hover = list(size = 10)  # 悬停时的尺寸
    ),
    hoveron = "points"   # 指定仅针对散点触发悬停事件
  )

# 保留背景图片并展示图表
plotly::layout(pp,
               images = list(
                 list(
                   source =  image_destination,
                   xref = "x",
                   yref = "y",
                   x = 0,
                   y = 2,
                   sizex = 100,
                   sizey = 4,
                   sizing = "stretch",
                   opacity = 1,
                   layer = "below"
                 )
               ))

关键修改说明

  • 利用style()函数的marker参数,分别设置默认尺寸和悬停状态下的尺寸
  • hoveron = "points"确保悬停事件只作用于散点,不会影响背景图片或其他元素
  • 原有背景图片的配置完全保留,满足你的必要需求

内容的提问来源于stack exchange,提问作者NM_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 05:07:19