Jon Nagra
Jon Nagra

Reputation: 1648

Modify aesthetic mapping in ggplot2 to obtain correct plotly legend

I have a ggplot2 chart that I want to render with plotly. The x and y variable are obtained from a character variable as in the example below:

library(ggplot2)
library(plotly)
dset <- data.frame(x =  runif(10), y = runif(10))
head(dset)
#>            x         y
#> 1 0.45902147 0.9842178
#> 2 0.04331170 0.8337590
#> 3 0.02202882 0.8607866
#> 4 0.27971306 0.4250171
#> 5 0.35531015 0.7182533
#> 6 0.61235609 0.9905286

# vars for x and y aesthetics
varx <- "x"
vary <- "y"

# ggplot2 chart
p <-
  ggplot(dset, aes(get(varx), get(vary))) + xlab(varx) + ylab(vary) + geom_point()

# convert to plotly
ggplotly(p)

The plotly output displays get(varx) in the tooltip and I would like it to display x. I believe the text is inherited from the aesthetic mapping.

print(p[[4]])
#> Aesthetic mapping: 
#> * `x` -> `get(varx)`
#> * `y` -> `get(vary)`

Created on 2020-01-20 by the reprex package (v0.3.0)

Is there a way to change the aesthetic mapping before converting the chart to plotly? If not, what is the easiest way to modify the tooltip in plotly?

Upvotes: 1

Views: 170

Answers (1)

David Jorquera
David Jorquera

Reputation: 2102

EDIT:

Just use aes_string() instead of aes(). The first requires to explicitly quote the inputs (instead of standard evaluation used by aes)

p <- ggplot(dset, aes_string(varx, vary)) + 
  xlab(varx) + 
  ylab(vary) + 
  geom_point()


ggplotly(p)

Original answer:

I managed to do it following this page: https://plot.ly/r/hover-text-and-formatting/, but you have to build the plot through plot_ly() function. It's more coding but you have more control over the plot's looks. From there you can paste the variables inside hovertemplate() and layout() for tooltip and axis labels.

dset %>% 
  plot_ly() %>% 
  add_trace(
    type = 'scatter',
    mode = 'markers',
    x = ~get(varx),
    y = ~get(vary),
    hovertemplate = paste(
      paste(varx,": %{x:.f}<br>"),
      paste(vary,": %{y:.f}<br>")
      )
  ) %>% 
  layout(xaxis = list(title = paste(varx)),
         yaxis = list(title = paste(vary)))

enter image description here

Upvotes: 1

Related Questions