Remove and alter legend in ggplot2 - r

I have the following plot but do not want the legend for point size to show. Also how can I change the title for the factor(grp)? Sorry I know this should be an easy one but I am stuck.
df1<-data.frame(x=c(3,4,5),y=c(15,20,25),grp=c(1,2,2))
p<-ggplot(df1,aes(x,y))
p<-p+ geom_point(aes(colour=factor(grp),size=4))
p
df2<-data.frame(x=c(3.5,4.5,5.5),y=c(15.5,20.5,25.5))
p<-p + geom_path(data=df2,aes(x=x,y=y))
p

To change the legend title, it's easier (I find) to just change the data frame title:
df1$grp = factor(df1$grp)
colnames(df1)[3] = "Group"
The reason why size appears in the legend, is because you have made it an aesthetic - it's not! An aesthetic is something that varies with data. Here size is fixed:
p = ggplot(df1,aes(x,y))
p = p+ geom_point(aes(colour=Group), size=4)
You can also change the name of the legend in ggplot itself:
p = p + scale_colour_discrete(name="Group")

Leave the size out of the aesthetics.
ggplot(df1,aes(x,y)) + geom_point(aes(colour = factor(grp)), size=4) +
scale_colour_discrete(name = "Grp")

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

Removing ggplot legend symbol while retaining label

Example code and figure:
data <- data.frame( ID = c(LETTERS[1:26], paste0("A",LETTERS[1:26])),
Group = rep(c("Control","Treatment"),26),
x = rnorm(52,50,20),
y = rnorm(52,50,10))
ggplot(data, aes(y=y,x=x, label=ID, color=Group)) +
geom_text(size=8) +
scale_color_manual(values=c("blue","red")) +
theme_classic() +
theme(legend.text = element_text(color=c("blue","red")))
What I'm trying to solve is removing the legend symbols (the "a") and coloring the Group labels (Control and Treatment) as they appear in the plot (Blue and Red respectively).
I've tried:
geom_text(show_guide = F)
But that just removes the legend entirely.
To keep it simple I could just use annotate...but wondering if there's a legend specific solution.
ggplot(data, aes(y=y,x=x, label=ID, color=Group)) +
geom_text(size=8, show_guide=F) +
scale_color_manual(values=c("blue","red")) +
theme_classic() +
annotate("text",label="Control", color="blue",x=20,y=80,size=8) +
annotate("text",label="Treatment", color="Red",x=23,y=77,size=8)
Another option is to use point markers (instead of the letter "a") as the legend symbols, which you can do with the following workaround:
Remove the geom_text legend.
Add a "dummy" point geom and set the point marker size to NA, so no points are actually plotted, but a legend will be generated.
Override the size of the point markers in the legend, so that point markers will appear in the legend key to distinguish each group.
ggplot(data, aes(y=y,x=x, label=ID, color=Group)) +
geom_text(size=8, show.legend=FALSE) +
geom_point(size=NA) +
scale_color_manual(values=c("blue","red")) +
theme_classic() +
labs(colour="") +
guides(colour=guide_legend(override.aes=list(size=4)))
Beginning with ggplot2 2.3.2, you can specify the glyph used in the legend using the argument key_glyph:
ggplot(data, aes(x=x, y=y, label=ID, color=Group)) +
geom_text(size=8, key_glyph="point") +
scale_color_manual(values=c("blue", "red")) +
labs(color=NULL) +
theme_classic()
For a full list of glyphs, refer to the ggplot2 documentation for draw_key. Credit to R Data Berlin for alerting me to this simple solution. Emil Hvitfeldt also has a nice blog post showcasing the options.
As a quick fix you can tweak the legend key, by hard coding the info you want, although around the other way - keep the key and remove the label.
library(grid)
GeomText$draw_key <- function (data, params, size) {
txt <- ifelse(data$colour=="blue", "Control", "Treatment")
# change x=0 and left justify
textGrob(txt, 0, 0.5,
just="left",
gp = gpar(col = alpha(data$colour, data$alpha),
fontfamily = data$family,
fontface = data$fontface,
# also added 0.5 to reduce size
fontsize = data$size * .pt* 0.5))
}
And when you plot you suppress the legend labels, and make legend key a bit wider to fit text.
ggplot(data, aes(y=y,x=x, label=ID, color=Group)) +
geom_text(size=8) +
scale_color_manual(values=c("blue","red")) +
theme_classic() +
theme(legend.text = element_blank(),
legend.key.width = unit(1.5, "cm"))

ggplot: Manually add legends for aesthetics that are not mapped

I want to produce a barplot overlayed with dots where both have separate legends. Also, I want to choose the color of the bars and the size of the dots using the arguments outside aes(). As both are not mapped, no legend is produced.
1) How can I add a legend manually for both fill and size?
library(ggplot2)
d <- data.frame(group = 1:3,
prop = 1:3 )
ggplot(d, aes(x=group, y=prop)) +
geom_bar(stat="identity", fill="red") +
geom_point(size=5)
This is what I came up with: I used dummy mappings and modified the legend according to my needs afterwards. But this approach appears clumsy to me.
2) Is there a manual way to say: Add a legend with this title, these shapes, these colors etc.?
d <- data.frame(dummy1="d1",
dummy2="d2",
group = 1:3,
prop = 1:3 )
ggplot(d, aes(x=group, y=prop, fill=dummy1, size=dummy2)) +
geom_bar(stat="identity", fill="red") +
geom_point(size=5) +
scale_fill_discrete(name="fill legend", label="fill label") +
scale_size_discrete(name="size legend", label="size label")
Above I mapped fill to dummy1. So I would expect scale_fill_discrete to alter this legend. But it appears to modify the size legend instead.
3) I am not sure what went wrong here. Any ideas?
I'm not sure why you say "Also, I want to choose the color of the bars and the size of the dots using the arguments outside aes()". Is it something you're trying to do or is it something that you have to do given how ggplot works?
If it's the latter, one solution is as under -
library(ggplot2)
d <- data.frame(group = 1:3,
prop = 1:3 )
ggplot(d, aes(x=group, y=prop)) +
geom_bar(stat="identity",aes( fill="label")) +
geom_point(aes(size='labelsize')) +
scale_fill_manual(breaks = 'label', values = 'red')+
scale_size_manual(breaks = 'labelsize', values = 5)

`fill` scale is not shown in the legend

Here is my dummy code:
set.seed(1)
df <- data.frame(xx=sample(10,6),
yy=sample(10,6),
type2=c('a','b','a','a','b','b'),
type3=c('A','C','B','A','B','C')
)
ggplot(data=df, mapping = aes(x=xx, y=yy)) +
geom_point(aes(shape=type3, fill=type2), size=5) +
scale_shape_manual(values=c(24,25,21)) +
scale_fill_manual(values=c('green', 'red'))
Resulting plot has a legend but it's 'type2' section doesn't reflect scale of fill value - is it by design?
I know this is an old thread, but I ran into this exact problem and want to post this here for others like me. While the accepted answer works, the less risky, cleaner method is:
library(ggplot2)
ggplot(data=df, mapping = aes(x=xx, y=yy)) +
geom_point(aes(shape=type3, fill=type2), size=5) +
scale_shape_manual(values=c(24,25,21)) +
scale_fill_manual(values=c(a='green',b='red'))+
guides(fill=guide_legend(override.aes=list(shape=21)))
The key is to change the shape in the legend to one of those that can have a 'fill'.
Here's a different workaround.
library(ggplot2)
ggplot(data=df, mapping = aes(x=xx, y=yy)) +
geom_point(aes(shape=type3, fill=type2), size=5) +
scale_shape_manual(values=c(24,25,21)) +
scale_fill_manual(values=c(a='green',b='red'))+
guides(fill=guide_legend(override.aes=list(colour=c(a="green",b="red"))))
Using guide_legend(...) with override_aes is a way to influence the appearance of the guide (the legend). The hack is that here we are "overriding" the fill colors in the guide with the colors they should have had in the first place.
I played with the data and came up with this idea. I first assigned shape in the first geom_point. Then, I made the shapes empty. In this way, outlines stayed in black colour. Third, I manually assigned specific shape. Finally, I filled in the symbols.
ggplot(data=df, aes(x=xx, y=yy)) +
geom_point(aes(shape = type3), size = 5.1) + # Plot with three types of shape first
scale_shape(solid = FALSE) + # Make the shapes empty
scale_shape_manual(values=c(24,25,21)) + # Assign specific types of shape
geom_point(aes(color = type2, fill = type2, shape = type3), size = 4.5)
I'm not sure if what you want looks like this?
ggplot(df,aes(x=xx,y=yy))+
geom_point(aes(shape=type3,color=type2,fill=type2),size=5)+
scale_shape_manual(values=c(24,25,21))

Customising legend size-symbol items in ggplot2

I'm mapping size to a variable with something like a log distribution - mostly small values but a few very large ones. How can I make the legend display custom values in the low-value range? For example:
df = data.frame(x=rnorm(2000), y=rnorm(2000), v=abs(rnorm(2000)^5))
p = ggplot(df, aes(x, y)) +
geom_point(aes(col=v, size=v), alpha=0.75) +
scale_size_area(max_size = 10)
print(p)
I've tried p + guides(shape=guide_legend(override.aes=list(size=8))) solution posted in this SO question, but it makes no difference in my plot. In any case I'd like to use specific legend size values e.g. v = c(10,25,50,100,250,500) instead of the default range e.g. c(100,200,300,400)..
Grateful for assistance.
To get different break points of size in legend, modify scale_size_area() by adding argument breaks=. With breaks= you can set breakpoints at positions you need.
ggplot(df, aes(x, y)) +
geom_point(aes(col=v, size=v), alpha=0.75) +
scale_size_area(max_size = 10,breaks=c(10,25,50,100,250,500))

Resources