条形图和 Plotly 中悬停的问题

问题描述 投票:0回答:1

我目前正在 R 中使用 Plotly,尝试创建条形图。下面,您可以找到我的数据和代码。

# Generating artificial data
set.seed(42)  # for reproducibility
n <- 50  # Number of data points
dat <- data.frame(
  PRODUCT_INDUSTRY_CODE = factor(sample(1:10, n, replace = TRUE)),
  revenue_before = runif(n, min = 100, max = 1000),  # Random values for revenue_before
  revenue_after = runif(n, min = 100, max = 1000),   # Random values for revenue_after
  PRODUCT_INDUSTRY_NAME = sample(c("Industry A", "Industry B", "Industry C", "Industry D", "Industry E"), n, replace = TRUE)
)

# Plotting
plt <- plot_ly(dat) %>% 
  add_trace(x = ~PRODUCT_INDUSTRY_CODE,  y = ~revenue_before, type = 'bar', name = 'Tax rate 1',hoverinfo = 'text', text = ~PRODUCT_INDUSTRY_NAME) %>% 
  add_trace(x = ~PRODUCT_INDUSTRY_CODE,  y = ~revenue_after, type = 'bar', name = 'Tax rate 2', hoverinfo = 'text', text = ~PRODUCT_INDUSTRY_NAME) %>% 
  layout(
    xaxis = list(title = ''), 
    yaxis = list(title = ''),
    barmode = 'group',
    title = ' '
  ) %>%
  layout(legend = list(orientation = 'h'))  # Set legend orientation to horizontal

plt

虽然代码成功生成了条形图,但我遇到了一个新问题。

具体来说,文本出现在图表的条形内部,这不是期望的结果。

我只希望当鼠标悬停在条形上方时该文本可见,而不是在条形内部可见。

任何人都可以提供有关如何解决此问题的帮助吗?

r plotly
1个回答
0
投票

您可以使用

textposition="none"
删除栏中的文本,并使用
hovertemplate
获得正确的悬停,如下所示:

library(plotly)
library(dplyr)

plt <- plot_ly(dat) %>% 
  add_trace(x = ~PRODUCT_INDUSTRY_CODE,  y = ~revenue_before, type = 'bar', name = 'Tax rate 1',hoverinfo = 'text', text = ~PRODUCT_INDUSTRY_NAME,
            textposition = "none", hovertemplate = "%{text}") %>% 
  add_trace(x = ~PRODUCT_INDUSTRY_CODE,  y = ~revenue_after, type = 'bar', name = 'Tax rate 2', hoverinfo = 'text', text = ~PRODUCT_INDUSTRY_NAME,
            textposition = "none", hovertemplate = "%{text}") %>% 
  layout(
    xaxis = list(title = ''), 
    yaxis = list(title = ''),
    barmode = 'group',
    title = ' '
  ) %>%
  layout(legend = list(orientation = 'h'))  # Set legend orientation to horizontal

plt

创建于 2024-03-20,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.