remove legend title in ggplot
RGgplot2R Problem Overview
I'm trying to remove the title of a legend in ggplot2
:
df <- data.frame(
g = rep(letters[1:2], 5),
x = rnorm(10),
y = rnorm(10)
)
library(ggplot2)
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom")
I've seen this question and none of the solutions there seem to work for me. Most give an error about how opts
is deprecated and to use theme
instead. I've also tried various versions of theme(legend.title=NULL)
, theme(legend.title="")
, theme(legend.title=element_blank)
, etc. Typical error messages are:
'opts' is deprecated. Use 'theme' instead. (Deprecated; last used in version 0.9.1)
'theme_blank' is deprecated. Use 'element_blank' instead. (Deprecated; last used in version 0.9.1)
I'm using ggplot2
for the first time since version 0.9.3 was released and I'm finding it difficult to navigate some of the changes...
R Solutions
Solution 1 - R
You were almost there : just add theme(legend.title=element_blank())
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
theme(legend.title=element_blank())
This page on Cookbook for R gives plenty of details on how to customize legends.
Solution 2 - R
This works too and also demonstrates how to change the legend title:
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
scale_color_discrete(name="")
Solution 3 - R
Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name
argument of the scale_
function to NULL
, i.e.
scale_fill_discrete(name = NULL)
(kudos to @pascal for a comment on another thread)
Solution 4 - R
Another option using labs
and setting colour to NULL
.
ggplot(df, aes(x, y, colour = g)) +
geom_line(stat = "identity") +
theme(legend.position = "bottom") +
labs(colour = NULL)
Solution 5 - R
For Error: 'opts' is deprecated
. Use theme()
instead. (Defunct; last used in version 0.9.1)'
I replaced opts(title = "Boxplot - Candidate's Tweet Scores")
with
labs(title = "Boxplot - Candidate's Tweet Scores")
. It worked!