R中ggplot2转Plotly后hover显示固定值问题求助
问题原因与解决办法
问题根源
yearmon是zoo包的自定义日期格式,ggplotly对这类非R原生的特殊日期类型兼容性不佳,无法正确将折线的每个数据点与对应的Month和deposit_insurance值建立关联,导致鼠标hover时只会固定显示数据集第一行的信息(Jan 2004, 52)。
解决步骤
方法1:转换为标准Date格式
把yearmon类型的Month列转成R原生的Date格式,让plotly能正常识别每个数据点的对应值:
# 先加载依赖包(未安装的话先运行install.packages(c("zoo", "ggplot2", "plotly"))) library(zoo) library(ggplot2) library(plotly) # 将yearmon格式转为Date格式 depins$Month <- as.Date(depins$Month) # 重新绘制交互式图表 p <- ggplot(depins, aes(x = Month, y = deposit_insurance)) + geom_line(color = "blue") + ggtitle("Frequency of 'deposit insurance' searches, 2004-present") + labs(x = "Month", y = "Frequency") ggplotly(p)
方法2:自定义hover文本
如果不想转换日期格式,也可以在aes中手动指定hover显示的内容,强制绑定每个点的对应数据:
library(zoo) library(ggplot2) library(plotly) p <- ggplot(depins, aes(x = Month, y = deposit_insurance, text = paste("Month:", format(Month, "%b %Y"), "\nFrequency:", deposit_insurance))) + geom_line(color = "blue") + ggtitle("Frequency of 'deposit insurance' searches, 2004-present") + labs(x = "Month", y = "Frequency") # 指定只显示自定义的hover文本 ggplotly(p, tooltip = "text")
内容的提问来源于stack exchange,提问作者James Rider
相关产品推荐
相关产品推荐

