How can I remove the legend title in ggplot2? - r

I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
I make a simple bar plot:
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
My question is: is there a way to remove the title ('Type') from the legend?
Thanks!

I found that the best option is to use + theme(legend.title = element_blank()) as user "gkcn" noted.
For me (on 03/26/15) using the previously suggested labs(fill="") and scale_fill_discrete("") remove one title, only to add in another legend, which is not useful.

You can modify the legend title by passing it as the first parameter to a scale. For example:
ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) +
geom_bar(position="dodge") +
theme(legend.position="top", legend.direction="horizontal") +
scale_fill_discrete("")
There is also a shortcut for this, i.e. labs(fill="")
Since your legend is at the top of the chart, you may also wish to modify the legend orientation. You can do this using opts(legend.direction="horizontal").

You can use labs:
p + labs(fill="")

The only way worked for me was using legend.title = theme_blank() and I think it is the most convenient variant in comparison to labs(fill="") and scale_fill_discrete(""), which also could be useful in some cases.
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(
legend.position="top",
legend.direction="horizontal",
legend.title = theme_blank()
)
P.S. There are more useful options in documentation.

You've got two good options already, so here's another using scale_fill_manual(). Note this also lets you specify the colors of the bars easily:
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
If you are using the up-to-date (As of January 2015) version of ggplot2 (version 1.0), then the following should work:
ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
theme(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))

#pascal 's solution in a comment to set the name argument of a scale function, such as scale_fill_discrete, to NULL, is the best option for me. It allows removing the title together with the blank space that would remain if you used "", while at the same time allowing the user to selectively remove titles, which is not possible with the theme(legend.title = element_blank()) approach.
Since it is buried in a comment, I am posting it as an answer to potentially increase its visibility, with kudos to #pascal.
TL;DR (for the copy-pasters):
scale_fill_discrete(name = NULL)

Related

ggplot only change the font of certain parts in the legend

Is it possible to put the scientific names of the fish in italics on the x-axis and in the legend and to use normal font for the rest?
In my case I would like that for example Barbatula barbatula (Bachschmerle) only Barbatula barbatula is in italics and (Bachscmerle) in the normal font
This is the bar chart right now
And this is a part of the data im using
My code is:
ggplot(R_Sandbach, aes(x = fct_infreq (Species), fill=Species ))+
geom_bar()+
theme_minimal()+
geom_text(aes(label=..count..), stat = "count", vjust = -.1, colour= "black")+
theme(axis.text.x = element_text(angle = 90, size = 5))+
xlab("Fischarten")+
ylab("Individuenanzahl")
ggtext is definitely a good option, although you can just manipulate aspects of your plot directly using theme as you've done in your question.
See an example below:
library(tidyverse)
ggplot() +
geom_blank() +
labs(x = "Fischarten", y = "Individuenanzahl", title = "My Super Awesome Title") +
theme(axis.title.x = element_text(face = "italic"),
plot.title = element_text(face = "italic"))
This produces a blank plot with the plot title and x axis both in italics. You can add as many changes into your theme() function as you like.
EDIT:
In the case of which you need specific words of your titles in italics, etc. you can manually incorporate html into your text and then format your plot to read this html.
In my personal experience this has sometimes caused issues with the general themes of ggplot.
Using this package library(mdthemes) solves the issues of html not being read as it should.
For example:
ggplot() +
geom_blank() +
labs(x = paste("<i>Fischarten</i>", "Other Title Stuff"), y = "Individuenanzahl", title = paste("My Super", "<i>Awesome Title</i>")) +
mdthemes::md_theme_classic()

Does anyone know why the title of my legend isn't updating? (ggplot2, stacked barplot)

For some reason, I can't get the title of my legend to update from "surv_status" (variable name) to "Survival Status" despite adding +labs(fill = "Survival status") in all different possible places in the code chunk.
Any suggestions? Thank you!
ggplot(data_train, aes(x = axil_nodes, fill = as.factor(surv_status))) +
geom_bar(position = "fill") +
labs(fill = "Survival status") +
theme_classic() +
xlab("Number of positive axillary nodes") +
ggtitle("Visualizing positive axillary node count by survival status") +
theme(legend.background = element_rect(color = "black", linetype = "dashed")) +
scale_fill_discrete(name = "surv_status", labels = c("Survived", "Deceased"))
There are a few different methods you can use to change the title of a legend with ggplot2. I know of three off the top of my head:
Use labs(fill= "Legend Title"), where fill can be replaced by whatever aesthetic modifier is associated with the legend.
Use scale_*_**() functions and name= argument. For example, scale_color_discrete(name="Legend Title")
Use guides() and declare title= within one of the guide functions. For example, guides(shape=guide_legend(title="Legend Title"))
If you address the title using more than one method, the priority goes:
guides() method
scale_*_**() method
labs() method
Use name associated with mapping - i.e. the name of your column you specify in the aes() function.
So the following example shows this clearly. You can move around each of those references to the gg object, but the priority seems to be maintained. The final legend in the plot with any ordering of the following code will result in the legend being named according to guides().
ggplot(df, aes(x,y, color=z)) + geom_point() +
guides(color=guide_legend(title='My other other legend')) +
scale_color_discrete(name='My Legend') +
labs(color='My other Legend')
If I remove the guides() part, the legend name is now reflective of scale_color_discrete():
ggplot(df, aes(x,y, color=z)) + geom_point() +
scale_color_discrete(name='My Legend') +
labs(color='My other Legend')
In your example, you have labs(fill = "Survival status") as well as scale_fill_discrete(name = "surv_status".... Using the rules above, you should understand that changing your labs() function will never take precedence over scale_fill_discrete(). You can either remove the argument of name from scale_fill_discrete() or change the value of name= within scale_fill_discrete() in order to change your legend title.

R: tailoring legend in ggplot boxplot leaves two separate legends

I have created a faceted boxplot using the ggplot2 package. The R code is as follows:
version.labs <- c(`1`="Version 1.0", `2`="Version 2.0", `3`="Version 3.0", `4`="Version 4.0", `5`="Version 5.0")
ggplot(df, aes(x=factor(Subsystem), y=Risk.value, fill=factor(Version)) ) +
geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(Version)), alpha=0.9) +
geom_boxplot(alpha = 0.5, show.legend = FALSE) + facet_grid(.~Version, labeller = as_labeller(version.labs)) +
theme(strip.text.x = element_text(size=9, color="black", face="bold"))
The resulting plot looks pretty good (as shown below) exept for the legend.
In the legend I want to change the title as well as the text label for each item. The title should be "Version" and the labels "Version 1.0", ..., "Version 5.0".
I've tried various ways but they all add a new separate legend. The new legend looks good, but the old one is still there which doesn't look good and I can't find a way to remove it.
The last thing I tried was to add the scale_color_manual() function, like this:
scale_color_manual(name = "Version", labels=c("v1.0","v2.0","v3.0","v4.0","v5.0"), values=c("grey","blue","green","red","black"))
This results in a boxplot that looks like this.
As can be seen there are two legends. So, close but no cigar. Any hints on how to solve this are appreciated.
I figured out the problem. It was that I had placed my aestetic fill function aes() in the general ggplot(). This should instead be placed in geom_boxplot(), otherwise both the general ggplot() as well as the geom_boxplot() will add a legend. So I fixed that, and then I used guides() to update the title in the geom_boxplot() legend. The full code looks as follows:
ggplot(df, aes(x=factor(Subsystem), y=Risk.value) ) +
geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(Version)), alpha=0.9) +
geom_boxplot(alpha = 0.5, show.legend = FALSE, aes(fill=factor(Version))) + facet_grid(.~Version, labeller = as_labeller(version.labs)) +
theme(strip.text.x = element_text(size=9, color="black", face="bold")) +
labs(x="Risk distribution per software version and subsystem type", y="Normalized risk value") +
guides(color=guide_legend("Version"))
The final plot looks like this, which I'm happy with.
You are using fill argument for grouping and generation of legend. may be instead of scale_color_manual you can use scale_fill_manual to override the existing legend

colored 100% barplot with ggplot2

Ia am completly new to R and just absolved the introduction from edX. Unfortunately it doesn't teach anything about ggplot2, what i want to use for my graphs in my thesis. I want to get 100% bar plots with different colours and if possible the value in the according bar. my data looks like this:
Concentration,Percentage,Phenotype
Control,0.933333333,0
Control,0.014814815,1
Control,0.022222222,2
Control,0.02962963,3
0.002,0.918181818,0
0.002,0.018181818,1
0.002,0.018181818,2
0.002,0.045454545,3
0.02,0.930434783,0
0.02,0.017391304,1
0.02,0.017391304,2
0.02,0.034782609,3
0.2,0.928571429,0
0.2,0.032467532,1
0.2,0.012987013,2
0.2,0.025974026,3
2,0.859813084,0
2,0.028037383,1
2,0.046728972,2
2,0.065420561,3
and the code i used is this:
ggplot(Inj, aes(x=Concentration, y=Percentage, fill=Phenotype))+geom_bar(stat='identity',color='black')
The resulting graph looks like that:
how can i change the color of the different bars and get the %-values in the bars?
Thanks for any help
You can make the colors controllable by making your fill variable a factor. Then you can manually adjust the colors like this
ggplot(Inj, aes(x=Concentration, y=Percentage, fill=factor(Phenotype)))+geom_bar(stat='identity',color='black') +
scale_fill_manual(values=c("red", "blue", "yellow", "pink"))
I don't recommend putting the values over the colors as they won't be visible for the very small values. I would use another way to visualize the data.
You can use scale_x_discrete to re-order the factors manually like this:
ggplot(Inj, aes(x=Concentration, y=Percentage, fill=Phenotype)) +
geom_bar(stat='identity',color='black') +
scale_fill_grey(start = .4, end = .9) +
theme_bw()+ylab("Distribution") +
xlab("Contentration [mg/ml]") +
ggtitle("Dose-respond analysis") +
theme(legend.title = element_text(colour="black", size=10, face="bold")) +
theme(legend.background = element_rect(fill="white",
size=0.5, linetype="solid",
colour ="black")) +
scale_x_discrete(limits=c('Control','0.002', '0.02', '0.2', '2'),
labels=c('Control\n(N=000)',
'0.002\n(N=000)',
'0.02\n(N=000)',
'0.2\n(N=000)',
'2\n(N=000)'))
I added the labels part to scale_x_discrete in response to your question in the comments below. You just need to update the N values. Notice that I put \n in each label in order to force the label text on to two lines so it wouldn't be jumbled. Just remove the \n if you'd prefer it to be on a single line.

Dodged geom_errorbar with geom_bar using fill, colour, and alpha

I am attempting to make a facet_wrap bar_graph with error bars (se) that clearly shows three different categorical variables (Treatment, Horizon, Enzyme) with one response variable (AbundChangetoAvgCtl). Below is the code for some dummy data followed by the ggplot code I have so far. The graphs I've made can be see at this link:
bargraph figures
Enzyme <- c("Arabinosides","Arabinosides","Arabinosides","Arabinosides","Arabinosides","Arabinosides","Cellulose","Cellulose","Cellulose","Cellulose","Cellulose","Cellulose","Chitin","Chitin","Chitin","Chitin","Chitin","Chitin","Lignin","Lignin","Lignin","Lignin","Lignin","Lignin")
Treatment <- c("Deep","Deep","Int","Int","Low","Low","Deep","Deep","Int","Int","Low","Low","Deep","Deep","Int","Int","Low","Low","Deep","Deep","Int","Int","Low","Low")
Horizon <- c("Org","Min","Org","Min","Org","Min","Org","Min","Org","Min","Org","Min","Org","Min","Org","Min","Org","Min","Org","Min","Org","Min","Org","Min")
AbundChangetoAvgCtl <- rnorm(24,mean=0,sd=1)
se <- rnorm(24, mean=0.5, sd=0.25)
notrans_noctl_enz_toCtl_summary <- data.frame(Enzyme,Treatment,Horizon,AbundChangetoAvgCtl,se)
ggplot(notrans_noctl_enz_toCtl_summary, aes(x=Horizon, y=AbundChangetoAvgCtl, fill=Horizon, alpha=Treatment)) +
geom_bar(position=position_dodge(), colour="black", stat="identity", aes(fill=Horizon)) +
geom_errorbar(aes(ymin=AbundChangetoAvgCtl-se, ymax=AbundChangetoAvgCtl+se),
width=.2,
position=position_dodge(.9)) +
scale_fill_brewer(palette = "Set1") + theme_bw() +
geom_hline(yintercept=0) +
labs(y = "Rel Gene Abundance Change / Control", x="") +
theme(axis.ticks = element_blank(),
axis.text.x = element_blank(),
strip.text.x = element_text(size=20),
plot.title = element_text(size=22, vjust=2, face="bold"),
axis.title.y = element_text(size=18),
legend.key.size = unit(.75, "in"),
legend.text = element_text(size = 15),
legend.title = element_text(size = 18)) +
facet_wrap(~Enzyme, scales="free")
(figure 1)
So this is close to what I want, however for some reason, the "alpha=Treatment" call in ggplot causes my errorbars to fade (which I don't want) as well as the bar_fill (which I do want). I've tried moving the "alpha=Treatment" to the geom_bar call, as well as adding "alpha=1" to geom_bar, but when I do that, the error bars all move to a single location and overlap (figure 2).
I initially wanted to cluster the bars within facet_wrap, but found the alpha option on this site, which seems to accomplish what I'm looking for as well. Any help would be appreciated. If there is a better way to represent all of this, those ideas are welcome as well.
Also, if there is a way to condense and clarify my legend, that would be extra bonus!
Thanks in advance for your help!
Mike
You need to assign Treatment to the group option in the ggplot() command and then move the alpha=Treatment option to the geom_bar() command. Then the alpha value of geom_errorbar won't be affected by the global option and will be black. Like this:
ggplot(notrans_noctl_enz_toCtl_summary, aes(x=Horizon, y=AbundChangetoAvgCtl, fill=Horizon, group = Treatment)) +
geom_bar(position=position_dodge(), colour="black", stat="identity", aes(fill=Horizon, alpha = Treatment))
Also, I would check whether setting alpha=Treatment corresponds to more transparent as being equivalent to low treatment and less transparent to high treatment. At least that would be my intuitive understanding, without any background on the research design or data.
For information about formatting legends, see here.

Resources