Reputation: 432
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.
Upvotes: 1
Views: 296
Reputation: 173858
If I understand you correctly, you want a clean fill legend and color legend side-by-side as in your picture at the top of the question. In this case, you can achieve the effect using guides
:
ggplot(mma, aes(group, frac, fill = kind, color = kind)) +
geom_col(position = posa, width = wd) +
geom_smooth(method = "loess", span = 0.15, size = 0.5) +
labs(x = "Time", y = "Populations", color = 'kind ') +
guides(fill = guide_legend(override.aes = list(colour = NA, alpha = 1)),
colour = guide_legend(override.aes = list(fill = 'white', alpha = 1))) +
theme(legend.position = c(0.66, 0.92),
legend.key.size = unit(0.56, 'lines'),
legend.direction = 'horizontal',
legend.box = 'horizontal')
Upvotes: 2
Reputation: 7540
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'
Created on 2022-04-28 by the reprex package (v2.0.1)
Upvotes: 3