I use ggbiplot
regularly and can control every aspect of the plot produced using ggplot2
tools, since it inherits from ggplot2
...
In ggplot2
, I usually control the number of columns in the legend with a line of the form:
ggplot2::guides(fill=ggplot2::guide_legend(ncol=2))
However, this does not seem to work in ggbiplot
(while everything else ggplot2
-related does work).
Please check the MWE below with iris
data, the only thing I want to do here is specify 2 columns for the legend (for illustration purposes, I know there are only 3 Species levels, but this was the example I had more at hand).
library(ggbiplot)
data(iris)
pca.obj <- prcomp(iris[,1:4], center=TRUE, scale.=TRUE)
P <- ggbiplot(pca.obj,
obs.scale = 1,
var.scale=1,
ellipse=T,
circle=F,
varname.size=3,
var.axes=T,
groups=iris$Species, #no need for coloring, I'm making the points invisible
alpha=0) + #invisible points, I add them below
ggplot2::theme_light() +
ggplot2::scale_color_manual("spec", values=c("red","black","pink"), guide=ggplot2::guide_legend(override.aes=list(shape=19, size=5, linetype=0))) +
ggplot2::guides(fill=ggplot2::guide_legend(ncol=2)) #THIS DOES NOT WORK HERE, WHY?
P$layers <- c(geom_point(aes(color=iris$Species), cex=3), P$layers) #add geom_point in a layer underneath (only way I have to change the size of the points in ggbiplot)
png(filename="test.png", height=600, width=600)
print(#or ggsave()
P
)
dev.off()
This produces the following biplot:
See how the number of columns in the legend never changes... Is there a way to specify the number of legend columns in ggbiplot
? Thanks
It'd be simpler to include the ncol = 2
in the first call to guide_legend()
. I.e.
library(ggbiplot)
data(iris)
pca.obj <- prcomp(iris[,1:4], center=TRUE, scale.=TRUE)
P <- ggbiplot(pca.obj,
obs.scale = 1,
var.scale=1,
ellipse=T,
circle=F,
varname.size=3,
var.axes=T,
groups=iris$Species, #no need for coloring, I'm making the points invisible
alpha=0) + #invisible points, I add them below
ggplot2::theme_light() +
ggplot2::scale_color_manual("spec", values=c("red","black","pink"), guide=ggplot2::guide_legend(ncol = 2, override.aes=list(shape=19, size=5, linetype=0))) # +
# ggplot2::guides(fill=ggplot2::guide_legend(ncol=2)) #THIS DOES NOT WORK HERE, WHY?
P$layers <- c(geom_point(aes(color=iris$Species), cex=3), P$layers) #add geom_point in a layer underneath (only way I have to change the size of the points in ggbiplot)
png(filename="test.png", height=600, width=600)
print(#or ggsave()
P
)
dev.off()
As Henrik says, it's down to a mismatch between fill =
and color =
.