Question

My data DT has the following structure:

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"))

head(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

However, the column names can be volatile, so I attempted to parameterise them in the ggplot call:

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

In the plot legend, how to display Ticker instead of eval(parse(text=var.col))?

Was it helpful?

Solution

There is no reason for funky eval(parse()) business:

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

OTHER TIPS

You can simply add a name to your color scale:

ggplot(DT, aes(x=Date, y=Value, colour=eval(parse(text=var.col)))) + geom_line() +
  scale_color_discrete(name=var.col)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top