R ggplot2 add a legend - r

As described, I want to add a legend to my graph.
nice_plot <- ggplot() +
geom_line(data = plot_dataframe_SD1, mapping = aes(x = XValues, y = YValues_SD1), color = "blue") +
geom_line(data = plot_dataframe_SD2, mapping = aes(x = XValues, y = YValues_SD2), color = "green") +
xlim(1, 2) +
ylim(1, 5) +
xlab("Standarard Deviation") +
ylab("AV") +
scale_fill_identity(name = 'the fill', guide = 'legend',labels = c('m1')) +
scale_colour_manual(name = 'the colour',
values =c('blue'='blue','green'='green'), labels = c('c2','c1'))
This is my code so far, btut it won't output a legend.
I also don't get an error message.
What is wrong with the code or what do I miss out?

Related

legend doesn't show - ggplot2

I have a problem with adding a legend to my plot. My code below:
ggplot(data = dane2, aes(x = iterations, y = powers, color = 'Moc testu')) +
geom_line(col = 'red')+
geom_line(data = dane3, aes(x = iterations, y = blad_II_r, color = 'Błąd II rodzaju')
, color = 'orange')+
ggtitle('Błąd II rodzaju i moc testu w zależności od ilości iteracji') +
xlab('iteracja') +
ylab('') +
ylim(-0.01, 1) +
scale_color_manual(name = "", values = c("Moc testu" = "red", "Błąd II rodzaju" = "orange"))+
guides(color = guide_legend(title = "Legenda")) +
theme(legend.position = 'right')
The legend doesn't show and I don't know why. Could you help?
I tried to plot with this code and it still doesn't work.
Thanks in advance!

Why do two legends appear when manually editing in ggplot2?

I want to plot two lines, one solid and another one dotted, both with different colors. I'm having trouble dealing with the legends for this plot. Take this example:
library(ggplot2)
library(reshape2)
df = data.frame(time = 0:127,
mean_clustered = rnorm(128),
mean_true = rnorm(128)
)
test_data_long <- melt(df, id="time") # convert to long format
p = ggplot(data=test_data_long,
aes(x=time, y=value, colour=variable)) +
geom_line(aes(linetype=variable)) +
labs(title = "", x = "Muestras", y = "Amplitud", color = "Spike promedio\n") +
scale_color_manual(labels = c("Hallado", "Real"), values = c("blue", "red")) +
xlim(0, 127)
print(p)
Two legends appear, and on top of it, none of them is correct (the one with the right colors has wrong line styles, and the one with the right line styles has all other things wrong).
Why is this happening and how can I get the right legend to appear?
You need to ensure all the aesthetic mappings match between the different aesthetics you're using:
library(ggplot2)
library(reshape2)
data.frame(
time = 0:127,
mean_clustered = rnorm(128),
mean_true = rnorm(128)
) -> xdf
test_data_long <- melt(xdf, id = "time")
ggplot(
data = test_data_long,
aes(x = time, y = value, colour = variable)
) +
geom_line(aes(linetype = variable)) +
scale_color_manual(
name = "Spike promedio\n", labels = c("Hallado", "Real"), values = c("blue", "red")
) +
scale_linetype(
name = "Spike promedio\n", labels = c("Hallado", "Real")
) +
labs(
x = "Muestras", y = "Amplitud", title = ""
) +
xlim(0, 127)
Might I suggest also using theme parameters to adjust the legend title:
ggplot(data = test_data_long, aes(x = time, y = value, colour = variable)) +
geom_line(aes(linetype = variable)) +
scale_x_continuous(name = "Muestras", limits = c(0, 127)) +
scale_y_continuous(name = "Amplitud") +
scale_color_manual(name = "Spike promedio", labels = c("Hallado", "Real"), values = c("blue", "red")) +
scale_linetype(name = "Spike promedio", labels = c("Hallado", "Real")) +
labs(title = "") +
theme(legend.title = element_text(margin = margin(b=15)))

Coloring the vertical lines by Class in ggplot

I want to plot the distribution of a variable by Class and add vertical lines denoting the means of the subsets defined by each Class and having them colored by Class. While I succeed to color the distributions by Class, the vertical lines appear gray. For a reproducible example see below:
library(data.table)
library(ggplot2)
library(ggthemes)
data(mtcars)
setDT(mtcars)
mtcars[, am := factor(am, levels = c(1, 0))]
mean_data <- mtcars[, .(mu = mean(hp)), by = am]
ggplot(mtcars, aes(x = hp, fill = am , color = am)) +
geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) + guides(color = FALSE) +
geom_density (alpha = 0.5)+
geom_vline(data = mean_data, xintercept = mean_data$mu, aes(color = as.factor(mean_data$am)), size = 2, alpha = 0.5) +
ggtitle("Hp by am") + scale_fill_discrete(labels=c("am" , "no am")) +
labs(fill = "Transmission") + theme_economist()
This code renders the following plot:
Your advice will be appreciated.
You need to include the xintercept mapping in your aes call, so that ggplot properly maps all the aesthetics:
ggplot(mtcars, aes(x = hp, fill = am , color = am)) +
geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) + guides(color = FALSE) +
geom_density (alpha = 0.5)+
geom_vline(data = mean_data, aes(xintercept = mu, color = as.factor(am)), size = 2, alpha = 0.5) +
ggtitle("Hp by am") + scale_fill_discrete(labels=c("am" , "no am")) +
labs(fill = "Transmission") + theme_economist()
Anything you put in a geom call that's not in aes gets treated as a one-off value, and doesn't get all the mapped aesthetics applied to it.

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")

Lineplot legend + ABLINE ggplot

I have the following ggplot and trying to add the legend and a geom_abline at median.
purple line is for 2013 prods and red is for 2014
This is what I did to generate the plot:
ggplot(prods[Year==2013,], aes(x = Date, y = Prod, group = SOM)) +
geom_line(lwd = 1.3, colour = "purple") +
ylab("Actual Productivity") + theme(axis.title.x=element_blank()) +
geom_line(data=prods[Year==2014,], aes(x = Date, y = Prod, group = SOM),lwd = 1.3, colour = "red") +
geom_abline(data = prods,h=median(Prod))+
scale_color_manual("Period", values = c("purple","red"), labels = c("2013","2014")) +
facet_wrap(~ SOM)
I am not getting any error but there is no legend nor abline is popping up on the image. Plot looks like
this:
any help would be highly appreciated.
regards,
As per aosmith's advice:
I did the following and was able to get the following plot:
ggplot(data=prods,aes(Date)) +
geom_line(data=prods[Year==2013,],aes(y=Prod, colour="red"),lwd = 1.3,) +
geom_line(data=prods[Year==2014,],aes(y=Prod, colour="blue"),lwd = 1.3) +
geom_hline(data=prods, aes(yintercept = median(Prod))) +
scale_colour_manual(name="Period",values=c("blue","red", "black"), labels = c("2014","2013", "Median")) +
ylab("Actual Prod") + xlab(" ") +
theme(axis.title.y = element_text(size = 15, vjust=0.3)) +
facet_wrap(~ SOM)
Plot looks like this:

Resources