Return call from ggplot object

后端 未结 2 1464
闹比i
闹比i 2021-01-19 23:15

I\'ve been using ggplot2 for a while now, and I can\'t find a way to get formula from ggplot object. Though I can get basic info with summary

相关标签:
2条回答
  • 2021-01-19 23:58

    You can store any R code as an expression with 'expression()' and then evaluate it with 'eval()'. e.g.

    p <- expression(qplot(data = mtcars, x = factor(cyl), geom = "bar", fill = factor(cyl)) + 
         scale_fill_manual(name = "Cylinders", value = c("firebrick3", "gold2", "chartreuse3")) + 
         stat_bin(aes(label = ..count..), vjust = -0.2, geom = "text", position = "identity") + 
         xlab("# of cylinders") + ylab("Frequency") + 
         opts(title = "Barplot: # of cylinders"))
    

    then

    eval(p)

    will produce the plot but the original code is still stored in the variable 'p' as an expression.

    so

    p

    produces

    expression(qplot(data = mtcars, x = factor(cyl), geom = "bar", 
        fill = factor(cyl)) + scale_fill_manual(name = "Cylinders", 
        value = c("firebrick3", "gold2", "chartreuse3")) + stat_bin(aes(label = ..count..), 
        vjust = -0.2, geom = "text", position = "identity") + xlab("# of cylinders") + 
        ylab("Frequency") + opts(title = "Barplot: # of cylinders"))
    

    which is what we started with.

    'eval()' can also evaluate a character string as an expression if parsed as text with parse(), e.g.

    eval(parse(text='f(arg=value)')

    0 讨论(0)
  • 2021-01-20 00:06

    It's not currently possible to go from a ggplot2 object to the code that (might have) created it.

    0 讨论(0)
提交回复
热议问题