R: 如何自定义plotly interactive hover window?

R: How to customize plotly interactive hover window?

这里我有 ggplotly 给出的交互式条形图。唯一的问题是当我在条形图上移动鼠标时,在“模型”类别中有一个奇怪的数字而不是 A 或 B(见图)。是否可以自定义 plotly 弹出窗口 windows?

   df <- data.frame (model  = c("A", "A","B","B"),
                      year = c("2022","2021","2022","2021"),
                      sale = c(350,170,300,150),
                      change = c(180,NA,150,NA),
                      percent = c(105.8,NA,100,NA),
                      info = c("180, 105.8%",NA,"300,100%",NA)
                      )




#ggplot
plot <- ggplot(df, aes(fill=year, y=model, x=sale)) + 
    geom_bar(position="dodge", stat="identity") + geom_text(aes(label=info, x=1.11*max(sale),), fontface='bold')+ xlim(0, 1.2*max(df$sale)) +
 theme(legend.position="bottom")+labs(fill = " ")+
  scale_fill_brewer(palette = "Paired")



ggplotly(plot)

出于某种原因,如果您使用 x=model 并翻转轴,效果会更好:

plot <- ggplot(df, aes(fill=year, x=model, y=sale)) + 
  geom_bar(position="dodge", stat="identity") + geom_text(aes(label=info,y=1.11*max(sale),), fontface='bold')+
  ylim(0, 1.2*max(df$sale)) +
  theme(legend.position="bottom")+labs(fill = " ")+
  scale_fill_brewer(palette = "Paired")+
  coord_flip()

ggplotly(plot)

就个人而言,我避免使用 ggplotly(),因为它经常以我不想要的方式格式化视觉效果。

完整的 plotly 方法可能如下所示:

plot_ly(
  data = df,
  x = ~sale,
  y = ~model,
  color = ~year,
  text = ~year,
  type = "bar") %>% 
  add_trace(
    x = ~max(df$sale) * 1.1,
    y = ~model,
    type = 'scatter',
    mode = 'text',
    text = ~info,
    showlegend = FALSE
  ) %>% 
  style(hovertemplate = paste("Sale: %{x}",
                              "Model: %{y}",
                              "Year: %{text}",
                              sep = "<br>"))

您也可以尝试将 style() 对象附加到您的 ggplotly() 对象。不过我不确定这是否有效。