how to add a legend in ggplot in r - r

I would like to include a legend inside the top right of my plot, indicating the parameter values of the plots.
ggplot() +
geom_line(data=data1, aes(x=x, y=y1), color='green', linetype = "twodash", size=0.5) +
geom_line(data=data2, aes(x=x, y=y2), color='red', linetype="longdash", size=0.5) +
geom_line(data=data3, aes(x=x, y=y3), color='blue') +
theme_classic() +
labs(x='input, x',
y='output, f(x)')
Can someone please say how this is done. Thanks.

I think this is a very good source of "what to do with ggplot"
http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/#changing-the-position-of-the-legend
from there
# Position legend in graph, where x,y is 0,0 (bottom left) to 1,1 (top right)
bp + theme(legend.position=c(1, 1))
should/could do it?

Related

ggplot2 scale_color_manual not making legend

Here is my code. I'm getting the plot I want but it doesn't have a legend for the colors. I have Grade.7.ELA.4s...White as green and Grade.7.Math.4s as blue and thought the scale_color_manual would create a legend but when I plot it no legend appears.
PerW.vs.7ELA4s <- ggplot(Explore, aes(Explore$Percent.White, value)) +
geom_point(aes(Percent.White, Grade.7.ELA.4s...White),
color="green", alpha=.55) +
geom_point(aes(Percent.White, Grade.7.Math.4s...White),
color="blue", alpha=.5) +
geom_smooth(aes(Percent.White, Grade.7.ELA.4s...White),
color="green", alpha=.55, se=F) +
geom_smooth(aes(Percent.White, Grade.7.Math.4s...White),
color="blue", alpha=.5, se=F) +
scale_color_manual(name="", values=c("ELA"="green", "Math"="blue")) +
labs(y="# 7th Grade ELA 4's", x="Percent White")

Separate stat_density for two density curves in ggplot2

I am trying to produce a ggplot that shows the histogram of the data as well as two density curves in which one has no adjust value and the other one has.
I tried the following code:
ggplot(df, aes_string(x=value))+
geom_histogram(aes(y=..density..), colour="grey", fill="grey", alpha=.3)+
geom_density(colour="red", fill="red", alpha=.3)+
stat_density(bw="SJ", alpha=0)+
geom_density(colour="blue", fill="blue", alpha=.3)+
stat_density(bw="SJ", adjust=5, alpha=0)+
theme_bw()
But this produces this graph with both curves overlapping 100%...
The .txt dataframe used is on my google drive
Thanks in advance!
Does adding a specific adjust argument to geom_density not do what you want?
ggplot(df, aes(x=value))+
geom_histogram(aes(y=..density..), colour="grey", fill="grey", alpha=.3)+
geom_density(colour="red", fill="red", alpha=.3, adjust = 1)+
geom_density(colour="blue", fill="blue", alpha=.3, adjust = 2)+
theme_bw()

Remove gaps in a stat_density2d ggplot chart without modifying XY limits

When I run this code:
ggplot() +
stat_density2d(data = Unit_J, aes(x=X, y=Y, fill=..level.., alpha=0.9), lwd= 0.05, bins=50, col="blue", geom="polygon") +
scale_fill_continuous(low="blue",high="darkblue") +
scale_alpha(range=c(0, 0.03), guide="none") +
xlim(-6600,-3800) + ylim(400,2500) +
coord_fixed(expand=FALSE) +
geom_point(data = Unit_J, aes(x=X, y=Y), alpha=0.5, cex=0.4, col="darkblue") +
theme_bw() +
theme(legend.position="none")
I get this plot:
I know that increasing in this case X lims would solve the problem of unclosed lines shown on the left and right.
However, I want to keep these limits unchanged so that those "bugs" don't appear, and simply they must be beyond the limits, somehow hidden without creating those horrible lines.
Is there any possibility?
EDIT (download data here):
In order to ease and reproduce the example, you can download the data here
The trick is to expand the canvas using xlim and ylim so that there is enough room for ggplot to draw complete contours around the data. Then you can use tighter xlim and ylim parameters within the coord_fixed term to show the window you want...
ggplot() +
stat_density2d(data = Unit_J, aes(x=X, y=Y, fill=..level.., alpha=0.9),
lwd= 0.05, bins=50, col="blue", geom="polygon") +
scale_fill_continuous(low="blue",high="darkblue") +
scale_alpha(range=c(0, 0.03), guide="none") +
xlim(-7000,-3500) + ylim(400,2500) + #expanded in x direction
coord_fixed(expand=FALSE,xlim=c(-6600,-3800),ylim=c(400,2500)) + #added parameters
geom_point(data = Unit_J, aes(x=X, y=Y), alpha=0.5, cex=0.4, col="darkblue") +
theme_bw() +
theme(legend.position="none")

Enlarge ggplot2 legend

I have this plot made in R with ggplot2
which is drawn by the following code:
ggplot(mtcars) +
geom_smooth(fill='grey', alpha=0.3, span=0.1, aes(x=mpg, y=hp, color='AAA',linetype='AAA')) +
geom_smooth(fill='grey', alpha=0.3, span=0.9, aes(x=mpg, y=hp, color='BBB',linetype='BBB')) +
scale_colour_manual(name='test', values=c('AAA'='chocolate', 'BBB'='yellow')) +
scale_linetype_manual(name='test', values=c('AAA'='dashed','BBB'='solid')) +
theme_minimal() +theme(legend.position = "top")
Problem: from the legend, it is not easy to understand that the "AAA" line is dashed, since the box is too small.
How can I enlarge it?
I would love to have something similar to:
Try
# create your legend guide
myguide <- guide_legend(keywidth = unit(3, "cm"))
# now create your graph
ggplot(mtcars) +
geom_smooth(fill='grey', alpha=0.3, span=0.1,
aes(x=mpg, y=hp, color='AAA',linetype='AAA')) +
geom_smooth(fill='grey', alpha=0.3, span=0.9,
aes(x=mpg, y=hp, color='BBB',linetype='BBB')) +
scale_colour_manual(name='test',
values=c('AAA'='chocolate', 'BBB'='yellow'),
guide = myguide) +
scale_linetype_manual(name='test',
values=c('AAA'='dashed','BBB'='solid'),
guide = myguide) +
theme_minimal() + theme(legend.position = "top")
See ?guide_legend and here.
This will give you
You can use keywidth and keyheight to manipulate how much the key "stretches" into both directions. With title.position, direction, etc you can further finetune the legend.
Note that since you have multiple legends that are merged, you need to specify the guide to all merged scales. I simplified this by creating the guide outside as an object first.

R - Background colour on ggplot split across a diagonal?

Using R, library(ggplot2)
I have a ggplot that is a perfect square. From the top left corner, to the bottom right corner, I have a line.
So say xlim(0,100), ylim(0,100) with geom_abline(intercept=100, slope=-1).
How do I make everything above the line have say a blue background and below a red?
library(ggplot2)
dat = data.frame(x=c(0,100), ymin=0, y=c(100,0), ymax=100)
ggplot(dat) +
geom_ribbon(aes(x, ymin=y, ymax=ymax), fill="blue") +
geom_ribbon(aes(x, ymin=ymin, ymax=y), fill="red") +
geom_abline(aes(intercept=100, slope=-1)) +
#geom_line(aes(x,y), lwd=1) + # If you just want a line with the same extent as the data
theme_bw()
And analogously for more general curves:
x=seq(0,100,0.1)
dat = data.frame(x=x, ymin=0, y=2*x + 3*x^2 - 0.025*x^3)
dat$ymax=max(dat$y)
ggplot(dat) +
geom_ribbon(aes(x, ymin=y, ymax=ymax), fill="blue") +
geom_ribbon(aes(x, ymin=ymin, ymax=y), fill="red") +
geom_line(aes(x,y), colour="yellow", lwd=1) +
theme_bw()

Resources