R Plotly 通过 hoovermode 显示 x 轴值

R Plotly show x-axis value via hoovermode

关注这个

我希望通过悬停模式“x”可以看到 x 值...所以我添加了一个额外的 add_trace 可以工作,但是它在 green/red 中有描述并且想要它是白色的

t <- tibble("one" = c(1,2,3,4,5,6,7,8,9),
            "two" = c(-5,6,9,-8,7,-1,5,2,1),
            "three" = c(2,5,6,9,8,7,8,4,5))

# 'bar' objects don't have these attributes: 'mode', 'line'
Plot <- plot_ly(t, x = ~one, y = ~two, type = 'bar', mode = NULL, line = NULL, name = ~ifelse(two < 0, yes = "two < 0", no = "two > 0"),   
                color = ~two < 0, colors = c("#28a745", "#dc3545"),
                yaxis = 'y2') %>%
  
  add_trace(type = "bar", 
            x = ~one, y = 0, 
            hoverinfo='text', 
            text = ~paste("X:", one),
            yaxis = "y", opacity = 0,
            showlegend=F
  ) %>%
  
  add_trace(x = ~one, y = ~three, type = 'scatter',  mode = 'lines',
                name = "three", line = list(color = "#ffc107"), color = NULL, yaxis = "y") %>%
  
  layout(title = "test",
         xaxis = list(titel = "one"),
         yaxis = list(side = 'right', 
                      title = 'three', 
                      showgrid = F, zeroline = F, 
                      showline = T),
         yaxis2 = list(side = 'left', title = 'two', 
                       showgrid = F, zeroline = F,
                       showline = T, overlaying = "y"),
         hovermode = "x")

我们可以通过为新迹线定义标记颜色来实现这一点marker = list(color = "#ffffff")

library(plotly)
library(dplyr)

t <- tibble("one" = c(1,2,3,4,5,6,7,8,9),
            "two" = c(-5,6,9,-8,7,-1,5,2,1),
            "three" = c(2,5,6,9,8,7,8,4,5))

# 'bar' objects don't have these attributes: 'mode', 'line'
Plot <- plot_ly(t, x = ~one, y = ~two, type = 'bar', mode = NULL, line = NULL, name = ~ifelse(two < 0, yes = "two < 0", no = "two > 0"),   
                color = ~two < 0, colors = c("#28a745", "#dc3545"),
                yaxis = 'y2') %>%
  
  add_trace(type = "bar", 
            x = ~one, y = 0, 
            hoverinfo='text', 
            text = ~paste("X:", one),
            yaxis = "y", opacity = 0,
            showlegend = FALSE,
            marker = list(color = "#ffffff")
  ) %>%
  
  add_trace(x = ~one, y = ~three, type = 'scatter',  mode = 'lines',
            name = "three", line = list(color = "#ffc107"), color = NULL, yaxis = "y") %>%
  
  layout(title = "test",
         xaxis = list(titel = "one"),
         yaxis = list(side = 'right', 
                      title = 'three', 
                      showgrid = F, zeroline = F, 
                      showline = T),
         yaxis2 = list(side = 'left', title = 'two', 
                       showgrid = F, zeroline = F,
                       showline = T, overlaying = "y"),
         hovermode = "x")

Plot