geom_smooth and geom_point do not have legends - r

I want to create a plot that looks like this:
x=1:20
y=sample(20)
df <- tibble(x=x,y=y)
ggplot(df,aes(x,y))+
geom_smooth()+
geom_point()
But the codes unabled to show legends.
Could anyone help me, thanks!

I'm perhaps being a bit over-literal in your requirements, but you could do:
tibble(x = 1:20, y = sample(20)) %>%
ggplot(aes(x, y)) +
geom_smooth(aes(linetype = "line")) +
geom_point(aes(shape = "point"), color = "red", size = 3) +
theme_gray(base_size = 20) +
theme(legend.position = c(0.75, 0.9),
legend.background = element_blank()) +
labs(shape = NULL, linetype = NULL)

You could set them inside their aes() as variables:
x <- 1:20
y <- sample(20)
library(ggplot2)
library(dplyr)
df <- tibble(x=x,y=y)
ggplot(df,aes(x,y))+
geom_smooth(aes(color = "line"))+
geom_point(aes(color = "point"))+
scale_color_manual(values = c("blue","red"))

With ggnewscale you could try:
library(tibble)
library(ggplot2)
library(ggnewscale)
x=1:20
y=sample(20)
df1 <- tibble(x=x, y=y)
ggplot(df1, aes(x, y))+
geom_smooth(aes(colour = "line"))+
scale_colour_manual(values = "black") +
labs(colour = NULL)+
new_scale_colour()+
geom_point(aes(colour = "point"))+
scale_colour_manual(values = "red")+
labs(colour = NULL)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
Created on 2022-11-27 with reprex v2.0.2

Related

plot data and their means in the same graph using ggplot

using the data set airquality I have written the following code:
library("tidyverse")
data(airquality)
airquality <- na.omit(airquality)
airquality$date <- as.Date(paste("1973", airquality$Month, airquality$Day,
sep="-"))
p1 <- ggplot(airquality, aes(x= date, y = Ozone, col=factor(Month))) +
geom_point() +
geom_line()
p1
Now I would like to plot in the same graph the mean of ozone for each months. How can I do this?
You could add the mean as a dashed line. The easiest way to do this might be to simply pass the data you want to a geom_line layer:
ggplot(airquality, aes(x = date, y = Ozone, col = factor(Month))) +
geom_point() +
geom_line(alpha = 0.5) +
geom_line(data = airquality %>%
group_by(Month) %>%
summarise(Ozone = mean(Ozone),
date = c(first(date), last(date)),
Month = mean(Month)),
linetype = 2, size = 1) +
scale_color_brewer(palette = "Set1") +
theme_minimal(base_size = 16)
If you just want points showing the mean, you could simplify things with stat_mean from ggpubr
ggplot(airquality, aes(x = date, y = Ozone, col = factor(Month))) +
geom_point() +
geom_line(alpha = 0.5) +
ggpubr::stat_mean(size = 5, shape = 21,
aes(fill = factor(Month)), color = "black") +
scale_color_brewer(palette = "Set1") +
scale_fill_brewer(palette = "Set1") +
theme_minimal(base_size = 16)
To join these dots up, you could do:
ggplot(airquality, aes(x = date, y = Ozone, col = factor(Month))) +
geom_point() +
geom_line(alpha = 0.5) +
geom_line(data = airquality %>%
group_by(Month) %>%
summarise(Ozone = mean(Ozone), date = mean(date)),
color = "black", linetype = 2) +
ggpubr::stat_mean(size = 5, shape = 21,
aes(fill = factor(Month)), color = "black") +
scale_color_brewer(palette = "Set1") +
scale_fill_brewer(palette = "Set1") +
theme_minimal(base_size = 16)

Cannot change ggplot boxplot legend name

I am using this code:
library(ggplot2)
library(reshape)
mtcars <- melt(mtcars, id="am")
mtcars$am <- as.character(mtcars$am)
p <- ggplot(mtcars, aes(x = variable, y = value)) +
geom_boxplot(aes(color = am), width = 0.4, size = 0.4, position = position_dodge(0.6),
outlier.shape=NA, notch=T) +
scale_color_manual(values = c("red", "blue")) +
guides(fill = guide_legend(reverse=TRUE)) +
scale_fill_discrete(name="No name", labels=c("A", "B")) + #Why does this line not work?
coord_flip()
p
Why do the legend name and variable names not change? How can I change them?
Does this solve your problem?
library(ggplot2)
library(reshape)
mtcars <- melt(mtcars, id="am")
mtcars$am <- as.character(mtcars$am)
p <- ggplot(mtcars, aes(x = variable, y = value)) +
geom_boxplot(aes(color = am), width = 0.4, size = 0.4, position = position_dodge(0.6),
outlier.shape=NA, notch=T) +
scale_color_manual(values = c("red", "blue"),
name="No name", labels=c("A", "B")) +
guides(fill = guide_legend(reverse=TRUE)) +
coord_flip()
p
The issue is that you don't use "fill" in the plot (you use "color"), so adjusting the "fill" scale doesn't have any effect.
Also, change guides(fill = guide_legend(reverse=TRUE)) to guides(color = guide_legend(reverse=TRUE)) to reverse the legend order.

How to add labels to multiple ggplot graphs (A, B, C)

I am trying to add the labels A, B, and C to the top left hand corner of each of these graphs. I have tried cowplot::draw_plot_label(), but nothing seems to work. Can anyone help?
These A, B and C labels are not the main title of each plot.
# Packages
library(ggplot2)
library(gridExtra)
library(cowplot)
# 1st plot
p1 <- ggplot(data = new_data %>%
filter(Species =="Sharksucker_Remora")) +
scale_colour_manual(values=c(Sharksucker_Remora="black"), labels = c("Sharksucker Remora")) +
geom_line(mapping = aes(x = Date, y = Proportion, group = Species, colour = Species)) +
xlab("") +
ylab("Proportion") +
theme(legend.position="top") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) + labs(colour = ~italic(M.alfredi)~"Hitchhiker Species:") +
theme(legend.key=element_blank())
# 2nd plot
p2 <- ggplot(data = new_data %>%
filter(Species !="Sharksucker_Remora")) +
geom_line(mapping = aes(x = Date, y = Proportion, group = Species, colour = Species)) +
scale_colour_manual(values=c(Golden_Trevally="goldenrod2", Red_Snapper="firebrick2", Juvenile_Remora="darkolivegreen3"), labels = c("Juvenile Remora", "Golden Trevally", "Red Snapper")) +
xlab("") + ylab("Proportion") + labs(colour = "") + theme(legend.position="top") + theme(legend.key=element_blank()) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
# 3rd plot
p3 <- ggplot(data = new_data_counts) +
geom_bar(mapping = aes(x = Date, y = Count), stat =
'identity') +
xlab("Date (2015-2019)") + ylab("Total"~italic
(M.alfredi)~"Sightings") +
draw_plot_label(label =c("C") + theme(axis.text.x =
element_text(angle = 90, vjust = 0.5, hjust = 1))
# The grid
grid.arrange(p1,p2,p3)
I suggest you use labs(..., tag = ...) and theme(plot.tag = element_text()).
The code show how you can format the main title (here centered with hjust = 0.5) and the tag inside the theme() function. See the reproducible example, below:
# Packages
library(ggplot2)
library(gridExtra)
# library(cowplot) # not necessary here
# Plots
p1 <- ggplot() +
labs(title = "plot 1", tag = "A") +
theme(plot.title = element_text(hjust = 0.5),
plot.tag = element_text())
p2 <- ggplot() +
labs(title = "plot 2", tag = "B") +
theme(plot.title = element_text(hjust = 0.5),
plot.tag = element_text())
grid.arrange(p1, p2)
If you want the tag (A, B, C) to be inside the plotting area, this post suggest to use plot.tag.position = c(x, y). See for example:
p3 <- ggplot() +
labs(title = "plot 3", tag = "C") +
theme(plot.title = element_text(hjust = 0.5),
plot.tag = element_text(),
plot.tag.position = c(0.1, 0.8))
p3
Have you tried the package egg?
https://cran.r-project.org/web/packages/egg/vignettes/Overview.html
library(tidyverse)
library(magrittr)
data <- list()
for(i in 1:6) data[[i]] <- rnorm(100,0,1)
data %<>% bind_cols() %>% setNames(paste0("var",1:6))
p1 <- ggplot(data,aes(x = var1, y = var2)) + geom_point()
p2 <- ggplot(data,aes(x = var3, y = var4)) + geom_point()
p3 <- ggplot(data,aes(x = var5, y = var6)) + geom_point()
egg::ggarrange(p1,p2,p3,ncol = 1,
labels = c("A","B","C"))
Another option is using the patchwork package with plot_annotation which has the tag_levels argument which gives the possibility to add tags like letters or numbers. First a reproducible example with letters:
library(patchwork)
library(ggplot2)
p1 <- ggplot(mtcars) +
geom_point(aes(hp, disp)) +
ggtitle('Plot 1')
p2 <- ggplot(mtcars) +
geom_boxplot(aes(gear, mpg, group = gear)) +
ggtitle('Plot 2')
p1 + p2 & plot_annotation(tag_levels = 'A')
Created on 2022-08-21 with reprex v2.0.2
Another option with numbers where you change the tag_levels to "1" like this:
p1 + p2 & plot_annotation(tag_levels = '1')
Created on 2022-08-21 with reprex v2.0.2
As you can see, the tags have letters or numbers. Check the links above for more information and options.

Add item to legend by theme options

I have a data frame d like this:
d <- data.frame("name" = c("pippo","pluto","paperino"),
"id" = c(1,2,3),"count" = c(10,20,30),
"pvalue"=c(0.01,0.02,0.05),
geneRatio=c(0.5,0.8,0.2),
type=c("KEGG","Reactome","Reactome"))
and I plot a dotplot using the library ggplot:
ggplot(data = d,aes(geneRatio,name,size=count,colour = pvalue)) +
geom_point()+
ggtitle("Significantly Pathways") +
xlab("Gene Ratio") +
ylab("Pathways")+
theme(axis.text.y = element_text(color=d$type))
This is the plot at the moment
I would like to add to legend the information of "type" contained in dataframe d.
I would like to have a new item in the legend with color red = Reactome and color black= KEGG
Not saying that this is a good idea, but you can add a nonsensical geom to force the adding of a guide:
d <- data.frame("name" = c("pippo","pluto","paperino"),
"id" = c(1,2,3),
"count" = c(10,20,30),
"value"=c(0.01,0.02,0.05),
geneRatio=c(0.5,0.8,0.2),
type=c("KEGG","Reactome","Reactome")
)
library(ggplot2)
ggplot(data = d, aes(geneRatio,name,colour = pvalue)) +
geom_point(aes(size=count))+
geom_polygon(aes(geneRatio,name,fill = type)) +
ggtitle("Significantly Pathways") +
xlab("Gene Ratio") +
ylab("Pathways") +
scale_fill_manual(values = c('Reactome'='red', 'KEGG'='black')) +
theme(axis.text.y = element_text(color=d$type))
geom_polygon may not work with your actual data, and you may not find a suitable 'nonsensical' geom. I agree with #zx8754, a facet would be clearer:
ggplot(data = d, aes(geneRatio,name,colour = pvalue)) +
geom_point(aes(size=count)) +
ggtitle("Significantly Pathways") +
xlab("Gene Ratio") +
ylab("Pathways") +
facet_grid(type ~ ., scales = 'free_y', switch = 'y')
You could accomplish this using annotate, but it is a bit manual.
ggplot(data = d, aes(geneRatio, name, size = count, colour = pvalue)) +
geom_point() +
ggtitle("Significantly Pathways") +
xlab("Gene Ratio") +
ylab("Pathways")+
theme(axis.text.y = element_text(color=d$type)) +
annotate("text", x = 0.25, y = 3.5, label = "Reactome", color = "red") +
annotate("text", x = 0.25, y = 3.4, label = "KEGG", color = "black")

alter facet_grid output in ggplot2

This is the current version of my figure:
require(MuMIn)
require(ggplot2)
data(Cement)
d <- data.frame(Cement)
dd <- melt(d,id.var = "y")
ggplot(dd,aes(x = y,y = value, group = variable)) +
geom_point(size = 2) +
theme_classic() +
facet_grid(variable ~ ., scales = "free") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
xlab("") +
ylab("") +
guides(colour = FALSE)
How can I
1) Alter this graph so that the X1, X2, X3, and X4 labels are on the left hand side and they read c("factor x^2","factor x^3","factor x^4","factor x^5"),
2) Is there a method for surrounding each panel with a box, to make them more distinguishable?
Try this,
library(ggplot2)
library(gtable)
p <- ggplot(mtcars, aes(mpg, cyl))+
facet_grid(gear~., labeller=label_both) + geom_point() +
theme(strip.text.y=element_text(angle=90)) + labs(y="")
g <- ggplotGrob(p)
g$layout[g$layout$name == "strip-right",c("l", "r")] <- 2
grid.newpage()
grid.draw(g)
A solution for question 1 (partial) and 2:
names(d) <- c("x^1","x^2","x^3","x^4","y")
dd <- melt(d,id.var = "y", variable.name="factor")
ggplot(dd, aes(x = y, y = value, group = factor)) +
geom_point(size = 2) +
theme_bw() +
facet_grid(factor ~ ., scales = "free", labeller = label_both) +
theme(axis.text.x = element_text(angle = 90, hjust = 1), panel.grid = element_blank()) +
xlab("") +
ylab("") +
guides(colour = FALSE)
which gives:
Using labeller is a good option (problem #1) and facet_grid and facet_wrap have a switch argument for moving facet labels around a bit (problem #2):
library("ggplot2")
x <- runif(100)
exp <- rep(1:4, each = 25)
y <- x^exp
df <- data.frame(x, y, exp)
# facet_grid
ggplot(df, aes(x, y)) +
facet_grid(exp ~ ., labeller = label_bquote(factor~x^.(exp)), switch = "y") +
geom_point() + labs(y="") +
theme(strip.background = element_blank()) # Remove facet border if you want
# facet_wrap
ggplot(df, aes(x, y)) +
facet_wrap(~ exp, ncol = 1, labeller = label_bquote(factor~x^.(exp)), switch = "y") +
geom_point() + labs(y="") +
theme(strip.background = element_blank())

Resources