When using aes(fill=kind) in both geom_bar and geom_smooth, I could not get a clean legend and the same plot as follows :
This is the script:
#!/usr/bin/env Rscript
## load
library(ggplot2)
library(dplyr)
mma <- data.frame(kind=c(rep('A',100), rep('BB', 100), rep('CC',100)),
group=c(rep(seq(0.1, 10, by=0.1),3)),
frac=runif(n=300, min=0, max=1))
### pic
wd <- 0.05
posa <- position_dodge(width=wd)
ppa <- ggplot(data=mma, aes(x=group, y=frac, group=kind))
geom_bar(aes(fill=kind), stat='identity', position=posa, width=wd)
geom_smooth(aes(fill=kind, color=kind), method="loess", span=0.15, size=0.5)
labs(x="Time", y="Populations")
## default mina.png
## guides(fill=guide_legend(ncol=3, byrow=TRUE), color="none") # minb.png
## guides(color=guide_legend(ncol=3, byrow=TRUE), fill="none") # minc.png
theme(legend.position=c(0.66, 0.92),
legend.key.size=unit(0.56, 'lines'))
### output
pf <- c(3, 7)
ggsave(file = "./mina.png", height = pf[1], width = pf[2])
I dont know why there is a blue line and a frame in the legend of minb.png
(It seems if comes from geom_smooth
).
I know the gray rect/box in minc.png
could omit by using alpha=1
in geom_smooth
. However, it will also erase the span region of loess line.
CodePudding user response:
You could add show.legend = FALSE
in your geom_smooth
:
library(tidyverse)
mma <- data.frame(kind=c(rep('A',100), rep('BB', 100), rep('CC',100)),
group=c(rep(seq(0.1, 10, by=0.1),3)),
frac=runif(n=300, min=0, max=1))
### pic
wd <- 0.05
posa <- position_dodge(width=wd)
ggplot(data=mma, aes(x=group, y=frac, group=kind))
geom_bar(aes(fill=kind), stat='identity', position=posa, width=wd)
geom_smooth(aes(fill=kind, color=kind), method="loess", span=0.15, size=0.5, show.legend = FALSE)
labs(x="Time", y="Populations")
## default mina.png
guides(fill=guide_legend(ncol=3, byrow=TRUE), color="none") # minb.png
## guides(color=guide_legend(ncol=3, byrow=TRUE), fill="none") # minc.png
theme(legend.position=c(0.66, 0.92),
legend.key.size=unit(0.56, 'lines'))
#> `geom_smooth()` using formula 'y ~ x'