简体   繁体   中英

Adding a legend to a ggplot2

I try to add a legend to my ggplot2 plots but it is not working out. Also the command show.legend does not change anything

Following the answer of this question ( Adding manual legend in ggplot ) I tried scal_colour_manueal but it did not work out

library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, group = kpi) ) +
  geom_line(color=color1, show.legend = T) 

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, group = kpi), colour = color2 , show.legend = T) 

ggp <- ggp +  
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)

How can I add a legend to this plot?

You shouldn't set colours outside of aes if you want them to depent on some variable of the data frame.

library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, col= kpi) ) +
  geom_line(show.legend = T) 

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, col= kpi), show.legend = T) 

ggp <- ggp +  
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)

情节

Another hint: ggplot works best, when data is "tidy" (see eg Hadley Wickham's R for Data Science ). Then solution could look like this (the gather -call reshapes / tidies the data so that it suits better to ggplot):

library(tidyverse)
library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

data <- gather(data, key = value_name, value = value, -Week, -kpi) ## tidy the data with "gahter"

ggplot(data, aes(x = Week, y = value, colour = value_name, group = value_name)) +
    geom_line() +
    facet_wrap(kpi ~ ., ncol = 1) +
    scale_colour_manual(name="Legend", values=c(color1, color2))

We could have two geom_line with their respective colors and then use facet_wrap

library(ggplot2)

ggplot(data) + 
  aes(x = Week, y = value2, group = kpi, colour = color2) +
  geom_line() +
  geom_line(aes( x = Week, y = value, group = kpi, color = color1)) + 
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM