如何修复ggplot2转plotly交互PCA图时的label美学警告?
问题解决:ggplot转plotly时的label美学警告与悬停显示样本名称问题
问题背景
使用ggplot2绘制PCA得分图并转换为plotly交互式图时,期望鼠标悬停显示样本名称,但运行代码后出现以下警告:
In ggplot2::geom_point(data = df_pcs, mapping = aes(x = PC1, y = PC2, :
Ignoring unknown aesthetics: label
尝试改用text美学后,交互式图中仍无法显示样本名称。
原代码如下:
library(dplyr) library(ggplot2) library(plotly) #(1) example data dat <- iris[1:4] Group <- iris$Species #(2) perform PCA df_pca <- prcomp(dat, center = TRUE, scale. = TRUE) df_pcs <- data.frame(df_pca$x, Group = Group) #(3) plot hull_group <- df_pcs %>% dplyr::mutate(Sample_Name = rownames(df_pcs)) %>% dplyr::group_by(Group) %>% dplyr::slice(chull(PC1, PC2)) p2 <- ggplot2::ggplot() + ggplot2::geom_polygon(data = hull_group, mapping = aes(x = PC1, y = PC2, fill = Group, group = Group), alpha = 0.2) + ggplot2::geom_point(data = df_pcs, mapping = aes(x = PC1, y = PC2, color = Group, label = rownames(df_pcs)), size = 3) + ggplot2::theme_bw() plotly::ggplotly(p2, tooltip = "label")
解决方案
问题原因
- ggplot2的
geom_point不支持label美学映射,因此会抛出"忽略未知美学"的警告。 - plotly通过
text美学识别悬停提示文本,但需要正确绑定样本名并在ggplotly中指定对应tooltip字段。
修改后的代码
library(dplyr) library(ggplot2) library(plotly) #(1) 示例数据 dat <- iris[1:4] Group <- iris$Species #(2) 执行PCA df_pca <- prcomp(dat, center = TRUE, scale. = TRUE) # 提前将行名转为样本名列,避免在aes中直接调用rownames df_pcs <- data.frame(df_pca$x, Group = Group, Sample_Name = rownames(df_pca$x)) #(3) 绘图 hull_group <- df_pcs %>% group_by(Group) %>% slice(chull(PC1, PC2)) p2 <- ggplot() + geom_polygon(data = hull_group, aes(x = PC1, y = PC2, fill = Group, group = Group), alpha = 0.2) + # 将label替换为text美学,绑定Sample_Name geom_point(data = df_pcs, aes(x = PC1, y = PC2, color = Group, text = Sample_Name), size = 3) + theme_bw() # ggplotly中指定tooltip为"text",即可显示样本名称 ggplotly(p2, tooltip = "text")
关键改动说明
- 提前将样本名(行名)转换为
df_pcs的Sample_Name列,让数据结构更清晰,避免在美学映射中直接使用rownames()。 - 将
geom_point中的label = rownames(df_pcs)替换为text = Sample_Name,text是plotly识别的悬停文本美学字段。 ggplotly的tooltip参数指定为"text",确保悬停时显示绑定的样本名称。如果需要同时显示其他信息(如分组、PC值),可以改为tooltip = c("text", "Group", "PC1", "PC2")。
内容的提问来源于stack exchange,提问作者Wang
相关产品推荐
相关产品推荐

