7

I have plotly graphics where I'd like to change axis tick mark labels to specific strings. Consider the following example:

library(plotly)
p <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)

enter image description here

Say I want to supress all numeric xaxis tick mark labels and instead only plot the string "min" at x = 4.5 and "max" at x = 8.

How can I achieve this in plotly?


Sidenote: I know this is possible for base R plots, e.g. here and in ggplot2 by setting scale_x_continuous(breaks = c(4.5, 8), labels= c("4.5" = "min", "8" = "max")).

Is there also a way to achieve this in plotly? ..Unfortunately the plotly docs don't seem to offer a solution..

symbolrush
  • 7,123
  • 1
  • 39
  • 67
  • 2
    I'm not sure about plotly, but you can convert a ggplot using the `ggplotly` function to get a similar result: `p2 = ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point(colour=hcl(255,100,65)) + theme_bw() + scale_x_continuous(breaks=5:8, labels=LETTERS[5:8]); ggplotly(p2)`. The theme can be tweaked a bit more to get closer to the p – eipi10 Sep 12 '18 at 06:25
  • 1
    I'm not all that familiar with the details of plotly, but perhaps the [help for `ticktext`](https://plot.ly/r/reference/#layout-xaxis-ticktext) could be useful. – eipi10 Sep 12 '18 at 06:27
  • 1
    In case it helps, this post goes through the workings of how `ggplotly` pipes from `ggplot2` to `plotly`. It shows how `plotly_json(p2)` would show what is being sent to `plotly` so that you might recreate it more directly inside your `plot_ly` function. https://moderndata.plot.ly/learning-from-and-improving-upon-ggplotly-conversions/ – Jon Spring Sep 12 '18 at 06:34

1 Answers1

9

Thanks to @eipi10 and @Jon Spring I could figure it out:

library(plotly)
plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length) %>% 
  layout(xaxis = list(tickvals = c(4.5, 8), ticktext = c("min", "max")))

This is exactly what I was searching for and produces:

enter image description here

symbolrush
  • 7,123
  • 1
  • 39
  • 67