I wondered if there exists a simple method for transforming base output in R into a nicer GGplot themed plot (such as theme_ipsum)?
Would appreciate any/all feedback on this given the PCA base plot example below.
install.packages("Gifi")
library(Gifi)
ABC6 <- ABC[,6:11]
fitord <- princals(ABC6)
plot(fitord)
CodePudding user response:
The ggplot2 function autoplot
is an S3 generic that allows users to define a way of creating a ggplot automatically from an object of a particular class. Although the authors of Gifi have written a base R plot method (Gifi:::plot.princals
) so that you can do plot(fitord)
, they haven't written an autoplot.princals
method to allow a ggplot to be created. However, it's not terribly difficult to do this yourself:
library(tidyverse)
autoplot.princals <- function(x) {
x$loadings %>%
as.data.frame() %>%
rownames_to_column() %>%
ggplot(aes(0, 0))
geom_segment(aes(xend = D1, yend = D2),
arrow = arrow(length = unit(3, "mm")))
geom_text(aes(D1, D2 ifelse(D2 > 0, 0.03, -0.03), label = rowname),
hjust = 0)
geom_hline(yintercept = 0, color = "gray", linetype = 2)
geom_vline(xintercept = 0, color = "gray", linetype = 2)
coord_cartesian(xlim = c(min(c(0.5 * -abs(x$loadings[,1]), x$loadings[,1])),
max(c(0.5 * abs(x$loadings[,1]),
1.5 * x$loadings[,1]))))
labs(x = "Component 1", y = "Component 2")
hrbrthemes::theme_ipsum()
}
Which means we can simply do:
autoplot(fitord)
And, to show this generalizes, we can do
autoplot(princals(mtcars))