You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly交互式弹窗中将forcat::age_group替换为Age Group

技术问询

基于以下提供的代码与数据,请问如何在交互式弹窗中隐藏forcats::age_group并将其修改为Age Group?

数据集(pop_hisp_df):

structure(list(age_group = c("<  5 years", "5 - 14", "15  -  24", 
"25  -  34", "35  -  44", "45  -  54", "55  -  64", "65  -  74", 
"75  -  84", "85 +", "<  5 years", "5 - 14", "15  -  24", "25  -  34", 
"35  -  44", "45  -  54", "55  -  64", "65  -  74", "75  -  84", 
"85 +"), Type = c("Males", "Males", "Males", "Males", "Males", 
"Males", "Males", "Males", "Males", "Males", "Females", "Females", 
"Females", "Females", "Females", "Females", "Females", "Females", 
"Females", "Females"), Value = c(-6, -13, -13, -15, -17, -15, 
-11, -6, -3, -1, 6, 12, 12, 14, 16, 15, 12, 7, 4, 2)), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))

原代码:

# Plot

library(tidyverse)
library(plotly)

gg_pop_gen = ggplot(pop_gen_df, aes(x = forcats::as_factor(age_group), y = Value, fill = Type))  +
  geom_bar(data = subset(pop_gen_df, Type == "Females"), stat = "identity") + 
  geom_bar(data = subset(pop_gen_df, Type == "Males"), stat = "identity") + 
  #geom_text(aes(label = paste0(abs(Value), "%"))) +
  #scale_y_continuous(labels = function(z) paste0(abs(z), "%")) +          # CHANGE
  scale_y_continuous(
    limits=c(-20,20),
    breaks=c(-15,-10,0,10,15),
    labels=paste0(c(15,10,0,10,15),"%")
  ) + 
  scale_fill_manual(name = "", values = c("Females"="#ED5151", "Males"="#6B6BD6"), labels = c("Females", "Males")) +
  ggtitle("FIGURE 4: TOTAL POPULATION BY AGE AND GENDER") +
  labs(x = "AGE GROUPS", y = "PERCENTAGE POPULATION", fill = "Gender") +
  theme_minimal() +
  theme(legend.position="bottom") +
  coord_flip()

# Interactive
ggplotly(gg_pop_gen) %>% 
  layout(
    legend = list(
      orientation = 'h', x = 0.3, y = -0.3, 
      title = list(text = '')
    )
  ) %>%
  reverse_legend_labels() %>% 
  layout(margin = list(l = 50, r = 50, b = 100, t = 50),
         annotations = list(x = 0.3, y = -0.3, text = "<b>Figure 3 & 4</b>: Data for Figure 3 and 4 was retrieved from: \n U.S. Census Bureau, American Community 5-Year Estimates",
                            xref='paper', yref='paper', showarrow = F, 
                            xanchor='right', yanchor='auto', xshift=0, yshift=0,
                            font = list(size = 10)))

解决方案

要修改plotly交互式弹窗(hover提示框)中的文本,替换掉forcats::as_factor(age_group)并改为Age Group,可以用以下两种方法:

方法1:在ggplot层重命名变量

直接在数据映射时给age_group重命名,让plotly自动识别新的标签:

gg_pop_gen = ggplot(pop_gen_df, aes(x = `Age Group` = forcats::as_factor(age_group),  # 重命名变量
                                    y = Value, fill = Type))  +
  geom_bar(data = subset(pop_gen_df, Type == "Females"), stat = "identity") + 
  geom_bar(data = subset(pop_gen_df, Type == "Males"), stat = "identity") + 
  scale_y_continuous(
    limits=c(-20,20),
    breaks=c(-15,-10,0,10,15),
    labels=paste0(c(15,10,0,10,15),"%")
  ) + 
  scale_fill_manual(name = "", values = c("Females"="#ED5151", "Males"="#6B6BD6"), labels = c("Females", "Males")) +
  ggtitle("FIGURE 4: TOTAL POPULATION BY AGE AND GENDER") +
  labs(x = "AGE GROUPS", y = "PERCENTAGE POPULATION", fill = "Gender") +
  theme_minimal() +
  theme(legend.position="bottom") +
  coord_flip()

# 后续交互式代码保持不变
ggplotly(gg_pop_gen) %>% 
  layout(
    legend = list(
      orientation = 'h', x = 0.3, y = -0.3, 
      title = list(text = '')
    )
  ) %>%
  reverse_legend_labels() %>% 
  layout(margin = list(l = 50, r = 50, b = 100, t = 50),
         annotations = list(x = 0.3, y = -0.3, text = "<b>Figure 3 & 4</b>: Data for Figure 3 and 4 was retrieved from: \n U.S. Census Bureau, American Community 5-Year Estimates",
                            xref='paper', yref='paper', showarrow = F, 
                            xanchor='right', yanchor='auto', xshift=0, yshift=0,
                            font = list(size = 10)))

这样hover提示框会直接显示Age Group作为该字段的标签,不会出现forcats::as_factor(age_group)。

方法2:修改plotly生成的hover文本

如果不想改动ggplot的映射逻辑,可以直接修改plotly对象的hover文本内容:

# 先生成基础交互式图
p <- ggplotly(gg_pop_gen) %>% 
  layout(
    legend = list(
      orientation = 'h', x = 0.3, y = -0.3, 
      title = list(text = '')
    )
  ) %>%
  reverse_legend_labels() %>% 
  layout(margin = list(l = 50, r = 50, b = 100, t = 50),
         annotations = list(x = 0.3, y = -0.3, text = "<b>Figure 3 & 4</b>: Data for Figure 3 and 4 was retrieved from: \n U.S. Census Bureau, American Community 5-Year Estimates",
                            xref='paper', yref='paper', showarrow = F, 
                            xanchor='right', yanchor='auto', xshift=0, yshift=0,
                            font = list(size = 10)))

# 解析plotly对象并替换hover文本
p_build <- plotly_build(p)
for(i in seq_along(p_build$x$data)){
  p_build$x$data[[i]]$text <- gsub("forcats::as_factor\\(age_group\\):", "Age Group:", p_build$x$data[[i]]$text)
}

# 显示修改后的图
p_build

这段代码会遍历所有绘图轨迹,把hover文本中forcats::as_factor(age_group):替换成Age Group:,达到修改弹窗内容的效果。

注意事项

原代码中数据集变量名为pop_hisp_df,但绘图时用了pop_gen_df,需要确保两者名称一致,否则会出现数据找不到的错误。


内容的提问来源于stack exchange,提问作者Ed_Gravy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:10:36