Home > OS >  How can I create a legend in ggplot which assigns names and colors to columns and not to values with
How can I create a legend in ggplot which assigns names and colors to columns and not to values with

Time:10-27

I have been looking up ideas to create legends in ggplot, yet all solutions only offer legends which divide the data of a single column in a dataframe in different groups by color and name with group = "columnname". This the head of the dataframe given:

ewmSlots ewmValues ewmValues2 ewmValues3
1 0.7785078 0.7785078 0
2 0.7198410 0.7491744 0
3 0.7333798 0.7412771 0
4 0.9102729 0.8257750 0
5 0.7243151 0.7750450 0
6 0.8706777 0.8228614 0

Now I want a legend that shows ewmValues, ewmValues2 and ewmValues3 in their respective names and colors.

To give a simple example other solutions I found would resolve something like this

time sex
lunch male
dinner female
dinner male
lunch female

where a legend would show sex and the colors to each sex, which is obviously not the issue I want to tackle here.

CodePudding user response:

What about just melting the data (let's call your above example a data frame named ewm)?

# With melt
ggplot(melt(ewm, id.vars = "ewmSlots"), aes(ewmSlots, value, color=variable, stat='identity'))  
  geom_line(size=1.4)   labs(color="")

If you are opposed to melting, the below gives the exact same thing:

# Without melt
ggplot(ewm, aes(ewmSlots))   
  geom_line(aes(y=ewmValues, color="ewmValues"), size=1.4)   
  geom_line(aes(y=ewmValues2, color="ewmValues2"), size=1.4)   
  geom_line(aes(y=ewmValues3, color="ewmValues3"), size=1.4)   
  labs(color="", y="value")
  • Related