making line legends for geom_density in ggplot2 in R - r

with ggplot2, I make the following density plot:
ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species))
The colour legend (for each Species value) appears as a box with a line through it, but the density plotted is a line. Is there a way to make the legend appear as just a colored line for each entry of Species, rather than a box with a line through it?

One possibility is to use stat_density() with geom="line". Only in this case there will be only upper lines.
ggplot(iris)+
stat_density(aes(x=Sepal.Width, colour=Species),
geom="line",position="identity")
If you need also the whole area (all lines) then you can combine geom_density() with show_guide=FALSE (to remove legend) and stat_density() than will add legend just with horizontal lines.
ggplot(iris) +
geom_density(aes(x=Sepal.Width, colour=Species),show_guide=FALSE)+
stat_density(aes(x=Sepal.Width, colour=Species),
geom="line",position="identity")

The show_guide function used in the answer by #liesb is deprecated under ggplot 3.0.0; it has been changed to show.legend:
ggplot(iris) +
geom_density(aes(x=Sepal.Width, colour=Species),show.legend=FALSE) +
stat_density(aes(x=Sepal.Width, colour=Species),
geom="line",position="identity", size = 0) +
guides(colour = guide_legend(override.aes=list(size=1)))

ggplot(iris) +
stat_density(aes(x=Sepal.Width, colour=Species),
geom="line",position="identity")
Will do want you want.

You can get around plotting the lines twice by
ggplot(iris) +
geom_density(aes(x=Sepal.Width, colour=Species),show_guide=FALSE) +
stat_density(aes(x=Sepal.Width, colour=Species),
geom="line",position="identity", size = 0) +
guides(colour = guide_legend(override.aes=list(size=1)))
ps: sorry for not commenting on the obviously correct answer -- lack of rep issues :)
pps: I realise the thread is quite old but it helped me today, so it might help someone else sometime...

Related

ggplot2: line connecting axis to point

data:
df<-data.frame(grp=letters[1:4],perc=runif(4))
First option:
First, create a second dataset that contains zeros for each group
df2<-rbind(df,data.frame(grp=df[,1],perc=c(0,0,0,0)))
Then plot with geom_points and geom_line:
ggplot(df,aes(y=perc,x=grp))+
geom_point()+
geom_line(data=df2, aes(y=perc, x=grp))+
coord_flip()
Which looks just fine. Just too much extra work to create a second dataset.
The other option is using geom_bar and making the width tiny:
ggplot(df,aes(y=perc,x=grp))+
geom_point()+
geom_bar(stat="identity",width=.01)+
coord_flip()
But this is also weird, and when I save to .pdf, not all of the bars are the same width.
There clearly has to be an easier way to do this, any suggestions?
Use geom_segment with fixed yend = 0. You'll also need expand_limits to adjust the plotting area:
ggplot(df, aes(y=perc, x=grp)) +
geom_point() +
geom_segment(aes(xend=grp), yend=0) +
expand_limits(y=0) +
coord_flip()

ggplot remove or replace the 'a' in geom_text legends

I trying to remove the little a in front of a legend but without any luck. Other possibility would be to create a legend or legend like text next to the graph but I am running out of ideas. Maybe someone can help me.
I plot on specific positions a red X and I want to point out, that the X marked things are imputed...
df <- data.frame(x=rnorm(10),y=rnorm(10))
ggplot(df, aes(x=x, y=y)) + geom_point() + geom_text(aes(x=0,y=0, color=factor(1)), label='X') +
scale_color_manual(values = 'red', name='imputed',labels='imputed') +
theme(legend.key=element_blank(), legend.title=element_blank())
I think the best result would be to replace the little a by a X. But I could not find any solution for it.
The problem is that you use geom_text to draw the cross.
A simple way to solve it is to use geom_point to plot the cross:
ggplot(df, aes(x=x, y=y)) + geom_point() + geom_point(aes(x=0,y=0, color=factor(1)), shape='X', size=5) +
scale_color_manual(values = 'red',labels='imputed') +
theme(legend.key=element_blank(), legend.title=element_blank())

How to change style settings in stacked barchart overlaid with density line (ggplot2)

I am trying to change the style settings of this kind of chart and hope you can help me.
R code:
set_theme(theme_bw)
cglac$pred2<-as.factor(cglac$pred)
ggplot(cglac, aes(x=depth, colour=pred2))
+ geom_bar(aes(y=..density..),binwidth=3, alpha=.5, position="stack")
+ geom_density(alpha=.2)
+ xlab("Depth (m)")
+ ylab("Counts & Density")
+ coord_flip()
+ scale_x_reverse()
+ theme_bw()
which produces this graph:
Here some points:
What I want is to have the density line as black and white lines separated by symbols rather than colour (dashed line, dotted line etc).
The other thing is the histogram itself. How do I get rid of the grey background in the bars?
Can I change the bars also to black and white symbol lines (shaded etc)? So that they would match the density lines?
Last but not least I want to add a second x or in this case y axis, because of flip_coord(). The one I see right now is for the density. The other one I need would then be the count data from the pred2 variable.
Thanks for helping.
Best,
Moritz
Have different line types: inside aes(), put linetype = pred2. To make the line color black, inside geom_density, add an argument color = "black".
The "background" of the bars is called "fill". Inside geom_bar, you can set fill = NA for no fill. A more common approach is to fill in the bars with the colors, inside aes() specify fill = pred2. You might consider faceting by your variable, + facet_wrap(~ pred2, nrow = 1) might look very nice.
Shaded bars in ggplot? No, you can't do that easily. See the answers to this question for other options and hacks.
Second y-axis, similar to the shaded symbol lines, the ggplot creator thinks a second y-axis is a terrible design choice, so you can't do it at all easily. Here's a related question, including Hadley's point of view:
I believe plots with separate y scales (not y-scales that are transformations of each other) are fundamentally flawed.
It's definitely worth considering his point of view, and asking yourself if those design choices are really what you want.
Different linetypes for densities
Here's my built-in data version of what you're trying to do:
ggplot(mtcars, aes(x = hp,
linetype = cyl,
group = cyl,
color = cyl)) +
geom_histogram(aes(y=..density.., fill = cyl),
alpha=.5, position="stack") +
geom_density(color = "black") +
coord_flip() +
theme_bw()
And what I think you should do instead. This version uses facets instead of stacking/colors/linetypes. You seem to be aiming for black and white, which isn't a problem at all in this version.
ggplot(mtcars, aes(x = hp,
group = cyl)) +
geom_histogram(aes(y=..density..),
alpha=.5) +
geom_density() +
facet_wrap(~ cyl, nrow = 1) +
coord_flip() +
theme_bw()

How to get scales to appear under each facet of ggplot2?

I would like that scales appear under each facet of ggplot2. The graph produced by the following code inserts the scales only in the last facet. It is probably simple but I can't seem to get a handle on this. Below is my R code.
ggplot(aes(x=month),data=tot.d.pred ) +
geom_line(aes(y=tot.diff.pred, colour="tot.diff.pred")) +
geom_point(aes(y=tot.diff.pred, colour="tot.diff.pred")) +
facet_wrap(~state_code, nrow=3) + ylab("diff_pred") + xlab("Month") +
scale_colour_manual("",breaks=c("tot.diff.pred"), values=c("red"))
Many thanks in advance!
Setting scales = "free_x" inside facet_wrap will print x-scales on every facet. If your data already has the same xmin and xmax in each facet, nothing else will change, otherwise you can specify limits with scale_x_continuous().

ggplot legend slashes

This must have annoyed someone in the past so excuse me if this is a duplicate and I will remove it. Slashes across legends when using geom_bar can be annoying. e.g.:
x <- c("a","b")
y <- c(1,2)
df <- as.data.frame(cbind(x,y))
a <- ggplot(df,aes(x=x,y=y,fill=x))
a + geom_bar(colour="black") + scale_fill_manual(values=c("white", "black"))
When I use coloured bars I use this work around, plotting bars without colours first e.g.
a + geom_bar() + geom_bar(colour="black",show_guide=FALSE) +
scale_fill_manual(values=c("white", "black"))
However when the fill is white this leaves an unsatisfying empty white box in the legend without a border. e.g.
I have fixed this in the past manually using graphics software but now I think this must be of use to enough people to ask a question here. Can we make ggplot plot the legend with the black outline only but without the slash?
this,
a + geom_bar() + geom_bar(colour="black",show_guide=FALSE) +
scale_fill_manual(values=c("white", "black")) +
opts(legend.key = theme_rect(fill = 'black'))
gave me this,
thanks to this site.
Alos, you get the same result using colour instead of fill (it might be argued that one is better than).
a + geom_bar() + geom_bar(colour="black",show_guide=FALSE) +
scale_fill_manual(values=c("white", "black")) +
opts(legend.key = theme_rect(colour = 'black'))
Important note: In modern versions of ggplot2 opts has been deprecated and replaced with theme, and theme_rect has been replaced by element_rect.
No that's what gives it it's outline. If you use a gray instead of white (with your trick) it's more distinguishable. You could also add background color to the legend to make it more distinguishable and keep it white. See the bottom of this page for more detail:
http://wiki.stdout.org/rcookbook/Graphs/Legends%20(ggplot2)/
i wish there were a less hackish way to do this.

Resources