I have a dataset with columns and points superimposed. The plotting is fairly simple but I can't seem to get geom_point to appear as a separate legend. Instead it defaults to combining the two.
I have tried adding the points as separate dataframe, mapping points as factors, and endless functions found on forums. Any hints?
Simplified example below:
library(ggplot2)
Site <- c("A", "B", "C", "A", "B", "C")
Year <- c(2020, 2020, 2020, 2019, 2019, 2019)
Geomean <- c(65,184,27,21,67,51)
Historical.Geomean <- c(76,81,44,76,81,44)
df <- data.frame(Site, Year, Geomean, Historical.Geomean)
df$Year <- as.factor(df$Year)
fw_ecoli_plot <-
ggplot(df) +
geom_col(aes(x=Site, y=Geomean, fill=Year), position="dodge") +
geom_point(aes(x=Site, y=Historical.Geomean),
color="black", pch=18, show.legend = T) +
theme_bw()
fw_ecoli_plot
How about this:
Site <- c("A", "B", "C", "A", "B", "C")
Year <- c(2020, 2020, 2020, 2019, 2019, 2019)
Geomean <- c(65,184,27,21,67,51)
Historical.Geomean <- c(76,81,44,76,81,44)
df <- data.frame(Site, Year, Geomean, Historical.Geomean)
df$Year <- as.factor(df$Year)
fw_ecoli_plot <-
ggplot(df) +
geom_col(aes(x=Site, y=Geomean, fill=Year), position="dodge" ) +
geom_point(aes(x=Site, y=Historical.Geomean, colour="Historical Mean"),
pch=18) +
scale_colour_manual(values="black") +
labs(colour="") +
theme_bw()
fw_ecoli_plot
By putting the values in aes
, you're basically generating a new factor variable and a legend.
If you put the the values outside of aes
-> ggplot won't create a legend. You can try it out:
df %>%
ggplot(aes(x=Site, y=Geomean))+
geom_col(aes(fill=Year), position="dodge") +
geom_point(aes(x=Site, y=Historical.Geomean, color="black"), pch=18, show.legend = T) +
scale_color_manual(values = c('black' = 'black'))+
guides(fill = guide_legend(override.aes = list(shape = NA)))+
theme_bw()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.