How to create a legend for lines in scatterplot? - r

I want to add a legend for the main diagonal and the regression line to the scatter plot.
What I have got now:
library(ggplot2)
df = data.frame(x = 1:10, y = 1:10)
p <- ggplot(df, aes(x, y)) +
geom_point(size=1.2) +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
geom_smooth(method="lm", se=FALSE, formula=y~x, colour="blue", fill=NA, size=1.2) +
geom_abline(intercept=0, slope=1, size=1.2, colour="red") +
geom_text(aes(x=max(df[,1])/1.4, y=max(df[,2])/1.2, label=lm_eqn(df)), colour="blue", parse=TRUE) +
# doesn't work: scale_colour_manual("Lines", labels=c("Main Diagonal", "Regression"), values=c("red", "blue")) +
labs(x="X", y="Y")

use show_guide=TRUE e.g.
p <- ggplot(df, aes(x, y)) +
geom_point(size=1.2) +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
geom_smooth(method="lm", se=FALSE, formula=y~x, colour="blue", fill=NA, size=1.2) +
geom_abline(aes(colour="red"),intercept=0, slope=1, size=1.2,show_guide=TRUE) +
geom_text(aes(x=max(df[,1])/1.4, y=max(df[,2])/1.2, label="lm_eqn(df)"), colour="blue", parse=TRUE) +
# doesn't work: scale_colour_manual("Lines", labels=c("Main Diagonal", "Regression"), values=c("red", "blue")) +
labs(x="X", y="Y") + opts(legend.position = 'left')
plus you can move legends about using things like+ opts(legend.position = 'left') to get it on the left. I suggest you look at the link provided by Tyler Rinker and also the following:
https://github.com/hadley/ggplot2/wiki/Legend-Attributes
Also no idea what lm_eqn ia so in my code i have surrounded it with "" so it will appear as it is written..

I could finally manage to create a legend for the regression and the diagonal line which is located in the bottom right corner and that makes sense:
p <- ggplot(df, aes(x, y)) +
geom_point(size=1.2) +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
geom_abline(aes(colour="red"),intercept=0, slope=1, size=1.2, aes(colour="1"), show_guide=TRUE) + # new code
geom_smooth(method="lm", se=FALSE, formula=y~x, fill=NA, size=1.2, aes(colour="2"), show_guide=TRUE) + # new code
scale_colour_manual("Lines", labels=c("Diagonal", "Regression"), values=c("red", "blue")) +
opts(legend.position = c(0.85, 0.15)) # relative values, must be set individually

Related

How to delete legend in ggplot with reression model?

I'd like to ask how to delete legend in ggplot with regression model.
I already added theme(legend.position = "None")
but the legend cannot be deleted. Could you tell me what I was doing wrong?
Extra question!!
In my current code, how to change the symbol size and shape between N0 and N1? I want more bigger size of 'open circle', and 'closed square' shape.
Many thanks!!!
ggplot(data=x, aes(x=agw, y=pgw)) +
geom_point (data=x, aes(x=agw, y=pgw, color=Nitrogen)) +
stat_smooth(method = 'lm', se=FALSE, color="Black") +
scale_color_manual(values = c("Dark gray","Black")) +
theme(legend.position = "None") +
geom_text(x=30, y=70, label="", size=3.5, col="Black") +
geom_text(x=30, y=60, label="", size=3.5, col="Black") +
scale_x_continuous(breaks = seq(0,80,10),limits = c(0,80)) +
scale_y_continuous(breaks = seq(0,80,10), limits = c(0,80)) +
theme_bw() +
theme(panel.grid = element_blank())
This should work in lack of reproducible data. Be careful that functions like theme_bw() use to remove previous theme() settings as mentioned by #Ronald. So it is better to add in the final part of the plot. For shapes, you can enable shape in aes() like this and format with scale_shape_manual() (the numbers inside belong to the shape you want):
library(ggplot2)
#Code
ggplot(data=x, aes(x=agw, y=pgw)) +
geom_point (data=x, aes(x=agw, y=pgw, color=Nitrogen,shape=Nitrogen,size=3)) +
stat_smooth(method = 'lm', se=FALSE, color="Black") +
scale_color_manual(values = c("Dark gray","Black")) +
scale_shape_manual(values = c(1,15))+
geom_text(x=30, y=70, label="", size=3.5, col="Black") +
geom_text(x=30, y=60, label="", size=3.5, col="Black") +
scale_x_continuous(breaks = seq(0,80,10),limits = c(0,80)) +
scale_y_continuous(breaks = seq(0,80,10), limits = c(0,80)) +
theme_bw() +
theme(panel.grid = element_blank(),
legend.position = 'none')
For the legend: add the argument show.legend = F inside geom_point. For the different point size: can you give us an example of your dataset? We may need to reshape it.
ggplot(data=x, aes(x=agw, y=pgw)) +
geom_point (data=x, aes(x=agw, y=pgw, color=Nitrogen), show.legend = F) +
stat_smooth(method = 'lm', se=FALSE, color="Black") +
scale_color_manual(values = c("Dark gray","Black")) +
theme(legend.position = "None") +
geom_text(x=30, y=70, label="", size=3.5, col="Black") +
geom_text(x=30, y=60, label="", size=3.5, col="Black") +
scale_x_continuous(breaks = seq(0,80,10),limits = c(0,80)) +
scale_y_continuous(breaks = seq(0,80,10), limits = c(0,80)) +
theme_bw() +
theme(panel.grid = element_blank())

ggplot: conflict between geom_text and ggplot(fill)

When I use geom_text on a ggplot, there is a conflict with the ggplot "fill" option.
Here is a clear example of the problem:
library(ggplot2)
a=ChickWeight
str(a)
xx=data.frame(level=levels(a$Chick),letter=1:50)
# a graph with the fill option alone
x11();ggplot(a, aes(x=Chick, y=weight,fill=Diet)) + geom_boxplot(notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
xlab("Chick") +
ylab("Weight")
# a graph with the geom_text option alone
x11();ggplot(a, aes(x=Chick, y=weight)) + geom_boxplot(notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
geom_text(data=xx, aes(x=level,y=450,label = letter)) +
xlab("Chick") +
ylab("Weight")
# a graph with the two option
x11();ggplot(a, aes(x=Chick, y=weight,fill=Diet)) + geom_boxplot(notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
geom_text(data=xx, aes(x=level,y=1750,label = letter)) +
xlab("Chick") +
ylab("Weight")
If you only want the fill to affect the boxplot, move the aes() into the boxplot. Any aes() aesthetics in the ggplot() call itself will be propagated to all layers
ggplot(a, aes(x=Chick, y=weight)) + geom_boxplot(aes(fill=Diet), notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
geom_text(data=xx, aes(x=level,y=1750,label = letter)) +
xlab("Chick") +
ylab("Weight")
you can also disable the fill= aesthetic in the text layer with fill=NULL
ggplot(a, aes(x=Chick, y=weight, fill=Diet)) + geom_boxplot(notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
geom_text(data=xx, aes(x=level,y=1750,label = letter, fill=NULL)) +
xlab("Chick") +
ylab("Weight")

Multiple indices in ggplot label

I would like to add a label containing multiple indices to a bar plot:
data<-as.data.frame(c("A"))
colnames(data)<-"A"
data$B<-5
ggplot(data, aes(x=A, y=B)) +
geom_bar(stat="identity", colour="black", position="dodge", size=0.25, width=0.8, alpha=0.8) +
annotate("text", x=1, y=2.5, label="some text")
I need to replace "some text" with "a1 a2 a3" where the numbers are in subscript. I tried the following but get errors:
annotate("text", x=1, y=0.4, parse=T, label=paste("a[1]","a[2]","a[3]",sep=" "))
The following does that:
ggplot(data, aes(x=A, y=B)) + geom_bar(stat="identity", colour="black", position="dodge", size=0.25, width=0.8, alpha=0.8) + annotate("text", x=1, y=2.5, label="~a[1]~a[2]~a[3]", parse=TRUE)

Overlay density of one variable on trend line

I have some data:
dat <- data.frame(x=rnorm(100,100,100),y=rnorm(100,100,100))
I can plot it with a local trend line:
ggplot(dat, aes(x,y)) + stat_smooth()
But I want to overlay a density curve, on the same plot, showing the distribution of x. So just add the previous graph to this one (the y-axis is different, but I only care about relative differences in the density curve anyway):
ggplot(dat, aes(x)) + geom_density()
I know there's stat_binhex() and stat_sum() etc showing where the data falls. There are only a few y values, so what gets plotted by stat_binhex() etc is hard to read.
You can plot a combination of histograms and density curves at both sides of the scatterplot. In the example below I also included a confidence ellipse:
require(ggplot2)
require(gridExtra)
require(devtools)
source_url("https://raw.github.com/low-decarie/FAAV/master/r/stat-ellipse.R") # in order to create a 95% confidence ellipse
htop <- ggplot(data=dat, aes(x=x)) +
geom_histogram(aes(y=..density..), fill = "white", color = "black", binwidth = 2) +
stat_density(colour = "blue", geom="line", size = 1.5, position="identity", show_guide=FALSE) +
scale_x_continuous("x-var", limits = c(-200,400), breaks = c(-200,0,200,400)) +
scale_y_continuous("Density", breaks=c(0.0,0.01,0.02), labels=c(0.0,0.01,0.02)) +
theme_bw() + theme(axis.title.x = element_blank())
blank <- ggplot() + geom_point(aes(1,1), colour="white") +
theme(axis.ticks=element_blank(), panel.background=element_blank(), panel.grid=element_blank(),
axis.text.x=element_blank(), axis.text.y=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank())
scatter <- ggplot(data=dat, aes(x=x, y=y)) +
geom_point(size = 0.6) + stat_ellipse(level = 0.95, size = 1, color="green") +
scale_x_continuous("x-var", limits = c(-200,400), breaks = c(-200,0,200,400)) +
scale_y_continuous("y-var", limits = c(-200,400), breaks = c(-200,0,200,400)) +
theme_bw()
hright <- ggplot(data=dat, aes(x=y)) +
geom_histogram(aes(y=..density..), fill = "white", color = "black", binwidth = 1) +
stat_density(colour = "red", geom="line", size = 1, position="identity", show_guide=FALSE) +
scale_x_continuous("y-var", limits = c(-200,400), breaks = c(-200,0,200,400)) +
scale_y_continuous("Density", breaks=c(0.0,0.01,0.02), labels=c(0.0,0.01,0.02)) +
coord_flip() + theme_bw() + theme(axis.title.y = element_blank())
grid.arrange(htop, blank, scatter, hright, ncol=2, nrow=2, widths=c(4, 1), heights=c(1, 4))
the result:

ggplot2 plot without axes, legends, etc

I want to use bioconductor's hexbin (which I can do) to generate a plot that fills the entire (png) display region - no axes, no labels, no background, no nuthin'.
As per my comment in Chase's answer, you can remove a lot of this stuff using element_blank:
dat <- data.frame(x=runif(10),y=runif(10))
p <- ggplot(dat, aes(x=x, y=y)) +
geom_point() +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0))
p + theme(axis.line=element_blank(),axis.text.x=element_blank(),
axis.text.y=element_blank(),axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),legend.position="none",
panel.background=element_blank(),panel.border=element_blank(),panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),plot.background=element_blank())
It looks like there's still a small margin around the edge of the resulting .png when I save this. Perhaps someone else knows how to remove even that component.
(Historical note: Since ggplot2 version 0.9.2, opts has been deprecated. Instead use theme() and replace theme_blank() with element_blank().)
Re: changing opts to theme etc (for lazy folks):
theme(axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.position="none",
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
plot.background=element_blank())
Current answers are either incomplete or inefficient. Here is (perhaps) the shortest way to achieve the outcome (using theme_void():
data(diamonds) # Data example
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut)) +
theme_void() + theme(legend.position="none")
The outcome is:
If you are interested in just eliminating the labels, labs(x="", y="") does the trick:
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut)) +
labs(x="", y="")
'opts' is deprecated.
in ggplot2 >= 0.9.2 use
p + theme(legend.position = "none")
Late to the party, but might be of interest...
I find a combination of labs and guides specification useful in many cases:
You want nothing but a grid and a background:
ggplot(diamonds, mapping = aes(x = clarity)) +
geom_bar(aes(fill = cut)) +
labs(x = NULL, y = NULL) +
guides(x = "none", y = "none")
You want to only suppress the tick-mark label of one or both axes:
ggplot(diamonds, mapping = aes(x = clarity)) +
geom_bar(aes(fill = cut)) +
guides(x = "none", y = "none")
xy <- data.frame(x=1:10, y=10:1)
plot <- ggplot(data = xy)+geom_point(aes(x = x, y = y))
plot
panel = grid.get("panel-3-3")
grid.newpage()
pushViewport(viewport(w=1, h=1, name="layout"))
pushViewport(viewport(w=1, h=1, name="panel-3-3"))
upViewport(1)
upViewport(1)
grid.draw(panel)
use ggeasy, it is more simple.
library(ggeasy)
p + theme_classic()+easy_remove_axes() + easy_remove_legend()
Does this do what you want?
p <- ggplot(myData, aes(foo, bar)) + geom_whateverGeomYouWant(more = options) +
p + scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
opts(legend.position = "none")
I didn't find this solution here. It removes all of it using the cowplot package:
library(cowplot)
p + theme_nothing() +
theme(legend.position="none") +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
labs(x = NULL, y = NULL)
Just noticed that the same thing can be accomplished using theme.void() like this:
p + theme_void() +
theme(legend.position="none") +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
labs(x = NULL, y = NULL)

Resources