ggplot aes eval(解析(文本))

时间:2014-03-13 11:00:56

标签: r ggplot2 eval

我的数据DT具有以下结构:

structure(list(Ticker = c("MSDLWI Index", "MSDLWI Index", "MSDLWI Index", "MSDLWI Index","MSDLWI Index", "MSDLWI Index", "NDLEACWF Index", "NDLEACWF Index", "NDLEACWF Index","NDLEACWF Index", "NDLEACWF Index", "NDLEACWF Index"), Date = structure(c(-1L, 89L, 180L, 272L, 364L, 454L, 15705L, 15793L, 15884L, 15978L, 16070L, 16136L), class = c("IDate", "Date")), Value = c(NA, -0.02925, -0.180118465104301, 0.124488001005151, 0.0497217814923236,0.0966385660152425, 0.0323951658690891, 0.0842289682913797, 0.00992717655157427, 0.0631103139013451, 0.0782204344979787, 0.00855027196875335)), .Names =c("Ticker", "Date", "Value"), row.names = c(NA, -12L),class=c("data.table","data.frame"))
  

头(DT,3)

         Ticker       Date      Value
1: MSDLWI Index 1969-12-31         NA
2: MSDLWI Index 1970-03-31 -0.0292500
3: MSDLWI Index 1970-06-30 -0.1801185

但是,列名称可能是易失性的,因此我尝试在ggplot调用中对它们进行参数化:

var.col="Ticker"
ggplot(DT, aes(x=Date, y=Value, colour=eval(parse(text=var.col)))) + geom_line()

http://i.stack.imgur.com/H3tbN.png

在图表图例中,如何显示Ticker而不是eval(parse(text=var.col))

2 个答案:

答案 0 :(得分:6)

没有理由进行时髦的eval(parse())业务:

ggplot(DT, aes_string(x="Date", y="Value", colour=var.col)) + 
    geom_line()

答案 1 :(得分:1)

您只需在色标中添加名称即可:

ggplot(DT, aes(x=Date, y=Value, colour=eval(parse(text=var.col)))) + geom_line() +
  scale_color_discrete(name=var.col)