如何在 ggplotly 中按值排序条形图时在条形图工具提示上显示变量名称

how to show variable name on barchart tooltip when bars are ordered by value in ggplotly

我有一个 ggplot,其中条形图按值排序并由 plotly::ggplotly 呈现以使其具有交互性。但是,在图表上,将鼠标悬停在条形图上会将变量名称显示为 reorder(category, n)

因此提示显示:

    reorder(category, n): xxx
    n: xxx
    subCategory: xxx

我需要的工具提示是这样的:

category: xxx
subCategory: xxx
n: xxx

有谁知道我该如何解决这个问题?我不知道该怎么办......

下面是我的情节代码:

library(dplyr)
library(ggplot2)
library(plotly)

df = data.frame(category=c('A','A', 'B', 'B','C','C', 'D','D'),
                subCategory = c('Y', 'N', 'Y', 'N', 'Y', 'N','Y', 'N'),
                n=c(120, 22, 45, 230, 11, 22, 100, 220))
df %>% 
  ggplot(aes(x=category, y=n, fill=subCategory))+
  geom_bar(stat='identity')

g=df %>% 
  ggplot(aes(x=reorder(category, n), y=n, fill=subCategory))+
  geom_bar(stat='identity')

ggplotly(g)

一个可能的解决方案是不在 ggplot 中使用 reorder,而是在将 x 轴传递给 ggplot 之前重新排序,例如:

g=df %>% arrange(n) %>% 
  mutate(category = factor(category, unique(category))) %>%
  ggplot(aes(x=category, y=n, fill=subCategory))+
  geom_bar(stat='identity')+
  labs(x = "Category")

ggplotly(g)

另一种选择是将 ggplot 中的参数设置为在 ggplotlytooltip 参数中使用,例如:

g=df %>% 
  ggplot(aes(x=reorder(category, n), y=n, fill=subCategory, 
             text = paste("category:", category), text2 = n, text3 = subCategory))+
  geom_bar(stat='identity')+
  labs(x = "Category")

ggplotly(g, tooltip = c("text","text2","text3"))

它能回答您的问题吗?