R Question

R: How to plot two different variables using ggplot2 and add legend label in R?

I am trying to plot two different measures of financial risk (strongly simplified, don't take it seriously). My intention is to plot both and add some label or legend to clarify the graph.


alpha <- 0
x <- c()
var <- c()
es <- c()
for (i in 1:999) {
alpha <- alpha + 1/1000
x[i] <- i/1000
var[i] <- qnorm(alpha, mean=0)
es[i] <- dnorm(qnorm(alpha))/(1-alpha)

df <- data.frame(x,var,es)
df <- melt(df,id=x)
ggplot(df) + geom_line(aes(x=, y=value)) + scale_colour_manual(values=c("red","blue"))

I have tried using ggplot2 (I am starting with this package yet) but it shows up errors everytime. I sense that there is something that I am missing or not completely understanding about melting data frames or using ggplot2.

Answer Source

A few things.

  1. Your melt call is not set up to get what you want.
  2. You're missing the value for x in your aes call in geom_line.
  3. You don't have a color in your geom_line aes call, so your scale_color_manual does nothing.

Below is the correct code to produce the plot below. Correcting the above gets what you want, colored lines for each variable plus a legend.

 df <- data.frame(x,var,es)

 df <- melt(df, id.vars = "x", measure.vars = c("var", "es"))

 ggplot(df, aes(x = x, y = value)) + 
      geom_line(aes(group = variable, color = variable)) +

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download