[英]How to show only some hoverinfo points on a line graph with Plotly in R
[英]How can I remove the size line in the hoverinfo of a Plotly chart in R?
我發現以下頁面指示如何為R中的繪圖圖表創建自定義懸停文本。
https://plot.ly/r/text-and-annotations/#custom-hover-text
這似乎完全符合我的要求,但是,當我將代碼(見下文)復制到RStudio中並在本地運行時,我的hoverinfo中又多了一行,顯示了size變量。
RStudio中圖表的屏幕截圖:
如何在hoverinfo中刪除此“ wt(size):1.835”行?
library(plotly)
p <- mtcars %>%
plot_ly(x = disp, y = mpg, mode = "markers", color = cyl, size = wt,
hoverinfo = "text",
text = paste("Displacement = ", mtcars$disp, "Miles Per Gallon = ", mtcars$mpg)) %>%
layout(title ="Custom Hover Text")
p
我可以實現您想要的功能,但這很丑陋,而且確實有點hack。 我對此並不感到驕傲,但是我們開始吧。
# Your plot
library(plotly)
p <- mtcars %>%
plot_ly(x = disp, y = mpg, mode = "markers", color = cyl, size = wt,
hoverinfo = "text",
text = paste("Displacement = ", mtcars$disp, "Miles Per Gallon = ", mtcars$mpg)) %>%
layout(title ="Custom Hover Text")
p
# Get the list for the plot
pp <- plotly_build(p)
# Pick up the hover text
hvrtext <- pp$data[[1]]$text
# Split by line break and wt
hvrtext_fixed <- strsplit(hvrtext, split = '<br>wt')
# Get the first element of each split
hvrtext_fixed <- lapply(hvrtext_fixed, function(x) x[1])
# Convert back to vector
hvrtext_fixed <- as.character(hvrtext_fixed)
# Assign as hovertext in the plot
pp$data[[1]]$text <- hvrtext_fixed
# Plot
pp
我來到這里尋找相同的解決方案,但經過一番討價還價,以上解決方案仍然有效,但后來我最終找到了正確的方法。 這里是:
將您的“大小”變量放入marker = list()
所以代替
plot_ly(x = disp, y = mpg, mode = "markers", color = cyl, size = wt,
hoverinfo = "text",
text = paste("Displacement = ", mtcars$disp, "Miles Per Gallon = ", mtcars$mpg))
您可以使用
plot_ly(x = disp, y = mpg, mode = "markers", color = cyl, marker=list(size=wt),
hoverinfo = "text",
text = paste("Displacement = ", mtcars$disp, "Miles Per Gallon = ", mtcars$mpg))
那對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.