P.Chakytei
P.Chakytei

Reputation: 414

legend matching the line type in ggplot2

With the code below I get a plot for two datasets. The geom_line for the first data is dotted line. However, in legend it doesn't appear as such.

library(ggplot2)
A = data.frame(x = rnorm(10),y=rnorm(10))
B = data.frame(x = rnorm(10),y=rnorm(10))

ggplot()+
  geom_line(data = A,aes(x,y,colour = "cat"),linetype = 2)+
  geom_line(data = B,aes(x,y,color = "dog"))+
  scale_colour_manual("", 
                      breaks = c("cat", "dog"),
                      values = c("blue", "red")) 

How do I get the legend as dotted line for cat?

Upvotes: 1

Views: 433

Answers (2)

chemdork123
chemdork123

Reputation: 13843

As OP asked about how to specify that "cat" gets a dashed line, I will add to the other answer to say that you should combine the data frames, but then you can use scale_linetype_manual() to specify the association of linetype to each factor of df$animal:

library(dplyr)

df <- A %>% 
  mutate( animal = "cat") %>% 
  bind_rows(B %>% 
              mutate( animal = "dog"))

ggplot(df, aes(x=x, y=y, linetype=animal)) +
  geom_line() +
  scale_linetype_manual(values=c('dog'='solid','cat'='dashed'))

The other way to do this is to NOT combine the data frames. This approach is discouraged, but it does still work and also still requires you to use scale_linetype_manual() to specify which linetype goes with each. In this case, the name of the label for each linetype is defined within aes(linetype=, rather than via a column created in a new dataset.

# without combining data frames
ggplot(mapping=aes(x=x,y=y)) +
  geom_line(data=A, aes(linetype='cat')) +
  geom_line(data=B, aes(linetype='dog')) +
  scale_linetype_manual(values=c('dog'='solid','cat'='dashed'))

Both approaches yield the same plot (differences may be observed due to different randomization seed):

enter image description here

Upvotes: 1

Robert Wilson
Robert Wilson

Reputation: 3407

For cases like this it is better to combine A and B into a new dataframe:

library(dplyr)

df <- A %>% 
  mutate( animal = "cat") %>% 
  bind_rows(B %>% 
  mutate( animal = "dog"))

ggplot()+
  geom_line(data = df ,aes(x,y,colour = animal, linetype = animal))

Upvotes: 1

Related Questions