【问题标题】:how to show variable name on barchart tooltip when bars are ordered by value in ggplotly当条形图在ggplotly中按值排序时如何在条形图工具提示上显示变量名称
【发布时间】:2020-08-12 22:08:09
【问题描述】:

我有一个 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)

【问题讨论】:

    标签: r ggplot2 r-plotly ggplotly


    【解决方案1】:

    一种可能的解决方案是不要在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"))
    

    它回答了你的问题吗?

    【讨论】:

    • 这正是我所需要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多