I am trying to make a PCA score plot using ggplot2, then convert the ggplot
object into interactive plotly. The interactive plot will show the sample name if the cursor will hover on a point.
Below is my minimum example, and it works quite well. but I got the following warning:
In ggplot2::geom_point(data = df_pcs, mapping = aes(x = PC1, y = PC2, : Ignoring unknown aesthetics: label
I tried to use text
aesthetics, but then the sample names are now shown in the interactive plot.
How can I fix this warning?
Thanks.
library(dplyr)
library(ggplot2)
library(poorly)
#(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")
CodePudding user response:
This works for me:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(ggplot2)
#library(poorly)
#(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(df_pcs, aes(text = rownames(df_pcs)))
ggplot2::geom_polygon(data = hull_group,
mapping = aes(x = PC1, y = PC2, fill = Group, group = Group),
alpha = 0.2, inherit.aes = FALSE)
ggplot2::geom_point(mapping = aes(x = PC1, y = PC2, color = Group),
size = 3)
ggplot2::theme_bw()
plotly::ggplotly(p2, tooltip = "text")
Created on 2023-01-08 by the reprex package (v2.0.1)
I think the problem was that text
and label
are not known aesthetics for the point geometry. If you put the text
aesthetic in the call to ggplot()
, then the warning goes away.