1

I have a dataframe which is as follows:

X       Y      Variable
0.351   4.453  a
0.352   4.423  a
0.353   4.422  a
...     ...    ...
...     ...    ...
...     ...    ...
0.351   5.656  b
0.352   5.431  b
0.353   5.222  b

And so on for different variables. I'll keep it short with 2 variables in the example.

I plotted the dataframe and I want a legend which shows the variable names but not the legend title.

ggplot(data=df, aes(x=df$X, y=df$Y, color=df$Variable))+
  geom_line(size=1)+
  labs(x = "x",
       y = "y") +
  theme_bw()

This gives a simple but clean graph, with a legend. But then I want to change the labels in the legend that shows up, remove the legend title, and change the color of the lines with scale_color_manual options. I can change the colors but I couldn't manage to do the other things because the legend disappears.

ggplot(data=df, aes(x=df$X, y=df$Y, color=df$Variable))+
  geom_line(size=1)+
  labs(x = "x",
       y = "y") +
  scale_color_manual(values=c("green","red")
                     breaks=c("a","b")) +
  theme_bw()

I know in the last code there is a missing option for the legend title. What am I doing wrong?

D.K.
  • 47
  • 7

2 Answers2

3

Here's an example of how to alter the legend title and labels. To remove the title completely, you can set name = NULL.

# Create data frame
df <- read.table(text = "X       Y      Variable
0.351   4.453  a
0.352   4.423  a
0.353   4.422  a
0.351   5.656  b
0.352   5.431  b
0.353   5.222  b", header = TRUE)

# Load libraries
library(ggplot2)

# Plot results
ggplot(data=df, aes(x=df$X, y=df$Y, color=df$Variable))+
  geom_line(size=1)+
  labs(x = "x",
       y = "y") +
  scale_color_manual(values=c("green","red"),
                     breaks=c("a","b"),
                     labels = c("Label one", "Label two"),
                     name = "My Legend Title") +
  theme_bw()

Created on 2019-04-25 by the reprex package (v0.2.1)

Dan
  • 11,370
  • 4
  • 43
  • 68
1

You can remove your legend title with labs(color="") since the color aes gives your legend the name:

library(ggplot2)
ggplot(data=df, aes(x=df$X, y=df$Y, color=df$Variable))+
  geom_line(size=1)+
  labs(x = "x",
       y = "y",
       color = NULL) +
  theme_bw()

Plot: your plot without legend name


Also working:

scale_color_discrete(name = NULL)

For further information check this thread here

Community
  • 1
  • 1
mischva11
  • 2,811
  • 3
  • 18
  • 34