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

时间:2016-11-25 20:42:09

标签: r plot ggplot2

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.

require(ggplot2)
library(reshape)

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.

1 个答案:

答案 0 :(得分:1)

一些事情。

  1. 您的melt来电未设置为获得您想要的内容。
  2. 您在x的{​​{1}}来电中错失了aes的价值。
  3. 您的geom_line color来电中没有geom_line,因此aes无效。
  4. 以下是生成下图的正确代码。纠正上述内容可获得您想要的内容,每个变量的彩色线条加上一个图例。

    scale_color_manual

    enter image description here