As a part of a more complex plot with several legends, one of the legends has only one entry. I want to remove the label from this particular legend and keep only the (edited) title.
df <- data.frame(x = 1, y = 1)
p <- ggplot(df, aes(x = x, y = y, color = factor(x))) +
geom_point()
p
Because I do some other manipulations of the legends using guides(foo = guide_legend(override.aes
, I was hoping to remove the labels in the same guide_legend
call using the label
argument.
From ?guide.legend
:
"label
: [...] If FALSE
then the labels are invisible."
Thus, I tried:
p + guides(color = guide_legend(title = "other",
label = FALSE))
But this gives an error:
# Error in (function (name) : grob 'NULL' not found
I then had a look at discrete_scale
, which has a labels
argument (now with an "s"). From ?discrete_scale
:
"labels
: NULL
for no labels."
Thus, I tried:
p + scale_color_discrete(name = "other",
labels = NULL)
...which generates an error:
# Error in data.frame(values = scale_map(scale, breaks), labels = I(scale_labels(scale)), :
# arguments imply differing number of rows: 1, 0
My current workaround is:
p + scale_color_discrete(name = "other",
labels = "")
However, as described above, I would prefer to remove the labels using guide_legend
call.
So my main question is:
How can I make label = FALSE
in guide_legend
work?
If the answer is "it's just doesn't work", how is the "labels
: NULL
for no labels." supposed to be used in scale_foo_bar
?
One of the ways to remove legend title is to use scale_fill_discrete() function with name=”” as argument. Here we use scale_fill_discrete() as we have the legend from “fill” argument while making barplots.
Example 1: Remove All Legends in ggplot2 We simply had to specify legend. position = “none” within the theme options to get rid of both legends.
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
Answer. Legend is a broad label used for a group of objects. Label is used for labeling specific elements.
Both label = FALSE
in guide_legend
and labels = NULL
in discrete_scale
are fixed in the development version ggplot2_1.0.1.9002
.
# install development version, see https://github.com/hadley/ggplot2/.
# install.packages("devtools")
devtools::install_github("hadley/scales")
devtools::install_github("hadley/ggplot2movies")
devtools::install_github("hadley/ggplot2")
p + guides(color = guide_legend(title = "other", label = FALSE))
# or:
# p + scale_color_discrete(name = "other", labels = NULL)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With