Control ggplot2 legend look without affecting the plot - r

I'm plotting lines with ggplot2 like this:
ggplot(iris, aes(Petal.Width,Petal.Length,color=Species)) + geom_line() + theme_bw()
.
I find legend marks to be small so I want them to be bigger. If I change the size, lines on the plot change too:
ggplot(iris, aes(Petal.Width,Petal.Length,color=Species)) + geom_line(size=4) + theme_bw()
.
But I only want to see thick lines in the legend, I want lines on the plot to be thin. I tried to use legend.key.size but it changes the square of the mark, not the width of the line:
library(grid) # for unit
ggplot(iris,aes(Petal.Width,Petal.Length,color=Species))+geom_line()+theme_bw() + theme(legend.key.size=unit(1,"cm"))
I also tried to use points:
ggplot(iris,aes(Petal.Width,Petal.Length,color=Species)) + geom_line() + geom_point(size=4) + theme_bw()
But of course it still affects both plot and legend:
I wanted to use lines for the plot and dots/points for the legend.
So I'm asking about two things:
How to change width of line in the legend without changing the plot?
How to draw lines in the plot, but draw points/dots/squares in the legend?

To change line width only in the legend you should use function guides() and then for colour= use guide_legend() with override.aes= and set size=. This will override size used in plot and will use new size value just for legend.
ggplot(iris,aes(Petal.Width,Petal.Length,color=Species))+geom_line()+theme_bw()+
guides(colour = guide_legend(override.aes = list(size=3)))
To get points in legend and lines in plot workaround would be add geom_point(size=0) to ensure that points are invisible and then in guides() set linetype=0 to remove lines and size=3 to get larger points.
ggplot(iris,aes(Petal.Width,Petal.Length,color=Species))+geom_line()+theme_bw()+
geom_point(size=0)+
guides(colour = guide_legend(override.aes = list(size=3,linetype=0)))

Related

Removing the original color outline in R when using a new pallette in a barplot

I am using plot_bar function in R to illustrate some data from a phyloseq class. I want to add some different colors to my plot, here the pallette Paired from the RColorBrewer package. For some reasons the bars end up still having the default color around them. Here you can see how it looks like: https://imgur.com/a/VSBvwtk
Any way I could get rid of them?
phylum.both.b <- plot_bar(both.b, fill="phylum") +
geom_bar(aes(color=phylum, fill=phylum), stat="identity") +
scale_y_continuous(expand=c(0,0)) +
labs(x="", y="Relative abundance") +
scale_fill_brewer(palette="Paired") +
theme(axis.text.x=element_blank()) +
facet_wrap(~Type, scale="free_x", ncol=4) +
facet_row(vars(Type), scales = 'free', space = 'free')
ggsave("PhylumBothBact.png", phylum.both.b, height=15, width=40, unit="cm")
You defined color = phylum in the creation of your plot, but never manually defined the color, so the default is still used. fill fills the bars with color in a bar plot and color outlines the bars.
Try adding scale_color_manual(values = NA)to your plot. Alternatively if you want the outline to match you could use scale_color_brewer(palette = "Paired")

Adding legend to a single line chart using ggplot

I just try to make a line chart and add a legend to it using ggplot in R. The following is my code.
ggplot(mtcars, aes(x=mpg, y=wt)) + geom_line(stat = "identity") + scale_fill_identity(name = "", guide = "legend", labels = c("myLegend"))
and I got the following:
The legend is not shown in the plot and what I want is the following:
which I plot using Matlab. Could anyone tell me how to do it in R? Thank you so much!!
You plot is not showing a legend, because there are no aesthetics mapped to the line. Basically, ggplot sees no reason to add a legend as there's only one line.
A simple way to get a legend is to map the line type to a character string:
ggplot(mtcars, aes(x=mpg, y=wt, lty = 'MyLegend')) + geom_line()
You can have a look at ?scale_linetype for information on how to modify tthat legend.
For example, use + scale_linetype('MyLegendTitle') to change the legend title.

Different orientations for multiple legends in ggplot2?

How can I produce a plot with two legends where one legend is vertical and the other legend is horizontal?
Using the iris data set, here is an example:
ggplot(iris,aes(x=Sepal.Width,y=Petal.Width,color=Species,size=Sepal.Length))+
geom_point() +
scale_size_continuous(breaks=c(seq(from=5,to=7,by=0.4))) +
facet_wrap(~Species,ncol = 2) +
theme(legend.position=c(.7,.2))
I would like to have the Species color legend remain vertical but have the Sepal.Length legend be horizontal below it. Is this possible?
Note: I understand that the faceting makes the color legend unnecessary. I am simply using this as an example.
You can control the features of particular legends using the guides interface.
ggplot(iris,aes(x=Sepal.Width,y=Petal.Width,color=Species,size=Sepal.Length))+
geom_point() +
scale_size_continuous(breaks=c(seq(from=5,to=7,by=0.4))) +
guides(size=guide_legend(direction='horizontal')) +
facet_wrap(~Species,ncol = 2) +
theme(legend.position=c(.7,.2))

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 do you alter the appearance of points in a ggplot2 legend? [duplicate]

This question already has answers here:
ggplot2: Adjust the symbol size in legends
(5 answers)
Closed 8 years ago.
For scatterplots with many points, one common technique is to reduce the size of the points and to make them transparent.
library(ggplot2)
ggplot(diamonds, aes(x, y, colour = cut)) +
geom_point(alpha = 0.25, size = 0.5) +
ylim(0, 12)
Unfortunately, the points in the legend are now too small and faint to see properly.
I would like a way to change the points in the legend independently of the plots in the main plot panel. It ought to be one of the setting contained in:
thm <- theme_get()
thm[grepl("legend", names(thm))]
I'm struggling to find the appropriate setting though. How do I change the point size?
You can use the function guide_legend() in package scales to achieve your effect.
This function allows you to override the aes values of the guides (legends) in your plot. In your case you want to override both alpha and size values of the colour scale.
Try this:
library(ggplot2)
library(scales)
ggplot(diamonds, aes(x, y, colour = cut)) +
geom_point(alpha = 0.25, size = 1) +
ylim(0, 12) +
guides(colour=guide_legend(override.aes=list(alpha=1, size=3)))
If you need to change formatting only in the legend you should use override.aes= and size= in guide_legend (see below). This will override size used in plot and will use new size value just for legend.
To get points in legend and lines in plot workaround would be add geom_point(size=0) to ensure that points are invisible and then in guides() set linetype=0 to remove lines and size=3 to get larger points.
ggplot(iris,aes(Petal.Width,Petal.Length,color=Species))+geom_line()+theme_bw()+
geom_point(size=0)+
guides(colour = guide_legend(override.aes = list(size=3,linetype=0)))

Resources