0

I would like to generate a hovertext for ggplotly() using aes() along the lines of

mapping <- aes(text = paste0(
    "Value: ",
    columnName
))

where columnName is a variable containing a column name as a string. Now, I don't want columnName recognized as a column name itself. If columnName == "col1" the result I want is

aes(text = paste0(
   "Value: ",
    col1
))

which evaluates to the aesthetic mapping `text` -> `paste0("Value: ", col1)`.

I have tried using aes_string(), but

columnName <- "col1"
aes_string(text = paste0(
    "Value: ",
    columnName
))

just evaluates to the aesthetic mapping `x` -> `Value:col1`.

How do I make this work?

NiklasvMoers
  • 309
  • 2
  • 13
  • I don't understand what your expected result is. – Roland Jun 04 '20 at 13:06
  • If ```columnName``` has the value e.g. ```col1```, I want ```aes(text = paste0("Value: ", col1)```. – NiklasvMoers Jun 04 '20 at 13:08
  • Yes, I read that. Problem is that it doesn't make any sense (if you understand ggplot2 and R). Do you want to create an unevaluated expression? – Roland Jun 04 '20 at 13:10
  • I would like the variable ```columnName``` evaluated and the value (a string) unquoted. – NiklasvMoers Jun 04 '20 at 13:12
  • It makes sense because ```col1``` will evaluate to the column ```data$col1``` which, by value recycling, makes ```paste0("Value: ", col1)``` evaluate to ```c("Value: value1", "Value: value2", ...)``` inside of the ```ggplot()``` call if ```data$col1``` contains the value ```c("value1", "value2", ...)```. Does this clear your question? – NiklasvMoers Jun 04 '20 at 13:15
  • 1
    Are you looking for `columnName <- as.name(columnName); mapping <- bquote(aes(text = paste0( "Value: ", .(columnName) )) )`? Obviously it needs to be `eval`uated later on. (I'm sure there is something similar and fancy in the tidyverse hell.) – Roland Jun 04 '20 at 13:16
  • Yes, this is just what I was looking for. Thank you! – NiklasvMoers Jun 04 '20 at 13:20

1 Answers1

2

Apparently OP wants to create an expression object in order to evaluate it later on. That can be achieved using bquote (or substitute or some function from the tidyverse wich probably involves exclamation marks):

columnName <- "col1"
columnName <- as.name(columnName) #first turn the character string into a quoted name
mapping <- bquote(aes(text = paste0(
  "Value: ",
  .(columnName) #this substitutes the name into the expression
))
)
#aes(text = paste0("Value: ", col1))
Roland
  • 127,288
  • 10
  • 191
  • 288