Plotly R 突出显示问题:当我点击一个栏时,突出显示看起来是错误的

Plotly R Highlight Problem: When I Click on a Bar, the Hightlighting Looks Wrong

我想在我的情节中添加一个功能,让人们可以点击一个栏并突出显示它。但是,当我尝试添加此功能时,我只能单击该栏并突出显示其中的一小部分(请参见下图)。我尝试实施此 中的建议,但无济于事。不胜感激。

这是我的代码:

number_of_debates_from_1803_1910 <- fread("~/projects/hansard-shiny/app-data/introduction/number_of_debates_from_1803_1910.csv")
  
  number_of_debates_from_1803_1910 %>%
    highlight_key() %>%
    plot_ly(
          x = ~decade, 
          y = ~no_of_debates, 
          type = 'bar', 
          text = ~paste0("Decade: ", "<b>", decade, "</b>", "\n",
                         "Number of Debates: ", "<b>", no_of_debates, "</b>", "\n"),
          hoverinfo = "text",
          marker = list(color = 'rgb(158,202,225)',
                        line = list(color = 'rgb(8,48,107)',
                                    width = 1.5))) %>% 
    highlight(on = "plotly_click", off = "plotly_doubleclick") %>%
    layout(barmode = "overlay"),
           xaxis = list(title = ""),
           yaxis = list(title = "")) %>%
    config(displayModeBar = F) 

这是我的数据:

decade,no_of_debates
1800,926
1810,2435
1820,2400
1830,7848
1840,7398
1850,8835
1860,10660
1870,14051
1880,31509
1890,31857
1900,49725
1910,5631

如果您愿意,也可以通过以下方式访问:

structure(list(decade = c(1800L, 1810L, 1820L, 1830L, 1840L,  1850L), no_of_debates = c(926L, 2435L, 2400L, 7848L, 7398L, 8835L )), row.names = c(NA, -6L), class = c("data.table", "data.frame" ))

点击条形图之前的绘图图片:

点击条形图后的图:

您真的很接近问题的解决方案。无论出于何种原因,class 对于您突出显示的数据都很重要。因此,例如,在您的数据中,decade 的 class 是 int,但是,它需要的是 factor。解决这个问题很简单

number_of_debates_from_1803_1910$decade <- as.factor(number_of_debates_from_1803_1910$decade)

number_of_debates_from_1803_1910 %>%
  highlight_key(~decade) %>%
  plot_ly(
    x = ~decade, 
    y = ~no_of_debates, 
    type = 'bar', 
    text = ~paste0("Decade: ", "<b>", decade, "</b>", "\n",
                   "Number of Debates: ", "<b>", no_of_debates, "</b>", "\n"),
    hoverinfo = "text",
    marker = list(color = 'rgb(158,202,225)',
                  line = list(color = 'rgb(8,48,107)',
                              width = 1.5))) %>% 
  highlight(~decade, on = "plotly_click",off = "plotly_doubleclick") %>%
  layout(barmode = "overlay")