ggplotly图例位置设置与多行Tooltip自定义问题
问题解决方案
问题1:Tooltip无内容且需分行显示指定信息
原代码中text参数未放置在aes()函数内部,导致ggplotly无法识别该自定义提示内容。需将text移入aes(),并使用HTML换行标签<br>实现字段分行展示:
aes( x = Date, y = Total_Value, fill = `Attribute Name`, text = paste0( "Date: ", Date, "<br>", "Attribute: ", `Attribute Name`, "<br>", "Total Value: ", Total_Value, "<br>", "Percentage: ", scales::percent(percentage) ) )
问题2:ggplotly中图例位置保持底部
ggplot的theme(legend.position = "bottom")设置不会被ggplotly完全继承,需在ggplotly()后调用layout()手动配置图例的方向与位置:
ggplotly(p, tooltip = "text") %>% layout( legend = list( orientation = "h", # 设置图例水平排列 x = 0.5, # 水平方向居中 xanchor = "center", # 锚点对齐中心 y = -0.2 # 向下偏移避免遮挡图表 ) )
完整修正代码
library(ggplot2) library(plotly) library(scales) data_counts<-structure(list(Date = c("December - 2023", "December - 2023", "December - 2023", "February - 2024", "February - 2024", "February - 2024", "January - 2024", "January - 2024", "January - 2024", "March - 2024", "March - 2024", "March - 2024"), `Attribute Name` = c("patients_have_both", "patients_have_ev_without_sg", "patients_have_sg_without_ev", "patients_have_both", "patients_have_ev_without_sg", "patients_have_sg_without_ev", "patients_have_both", "patients_have_ev_without_sg", "patients_have_sg_without_ev", "patients_have_both", "patients_have_ev_without_sg", "patients_have_sg_without_ev" ), Total_Value = c(152, 28, 821, 163, 27, 899, 157, 27, 854, 169, 27, 953), percentage = c(0.151848151848152, 0.027972027972028, 0.82017982017982, 0.149678604224059, 0.0247933884297521, 0.825528007346189, 0.151252408477842, 0.0260115606936416, 0.822736030828516, 0.147084421235857, 0.0234986945169713, 0.829416884247171)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -12L), groups = structure(list( Date = c("December - 2023", "February - 2024", "January - 2024", "March - 2024"), .rows = structure(list(1:3, 4:6, 7:9, 10:12), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -4L), .drop = TRUE)) p<-ggplot(data_counts, aes(x = Date, y = Total_Value, fill = `Attribute Name`, text = paste0( "Date: ", Date, "<br>", "Attribute: ", `Attribute Name`, "<br>", "Total Value: ", Total_Value, "<br>", "Percentage: ", scales::percent(percentage) ))) + geom_bar(stat = "identity",width = 0.3) + labs(x = "Month of Flatiron Data Cutoff", y = "Patient Counts", title = "ADC Uptake over time among advanced UC") + scale_fill_manual(values = c("lightblue", "darkblue", "maroon")) + theme_minimal() + theme( legend.position = "bottom" ) ggplotly(p,tooltip = "text") %>% layout( legend = list( orientation = "h", x = 0.5, xanchor = "center", y = -0.2 ) )
关键修改说明
- Tooltip修复:将
text参数移入aes()内部,确保ggplotly能读取自定义提示内容;用<br>实现换行,清晰展示每个字段信息。 - 图例位置修复:通过
layout()设置图例为水平排列,调整坐标使其居中显示在图表底部,避免遮挡图表内容。
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

