Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Different axis label format depending on value using plotly

I have a plot and I would like values >= 0 to be formatted as a percent, and values < 0 to be formatted as a number. I know I can accomplish this by combining ggplot and plotly as shown below:

library(tidyverse)
library(plotly)

df <- data.frame(x = -5:5,
                 y = 0:10) 

p1 <- df %>% 
  ggplot(aes(x = x, y = y)) +
  geom_point() +
  scale_x_continuous(labels = function(x) paste0(x, ifelse(x >= 0, "%", "")))

ggplotly(p1)

enter image description here

However, I would like to accomplish this all using native plotly syntax without the ggplotly wrapper. Can anyone tell me how I would do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df %>% 
  plot_ly %>% 
  add_markers(x = ~x,
              y = ~y)

>Solution :

One option would be to get a vector of your desired breaks and to set these breaks and your labels via layout like so:

Note: For the breaks I use scales::breaks_extended()(range(df$x)) which gives us the default breaks used by scale_x_continuous.

library(plotly)

df <- data.frame(x = -5:5,
                 y = 0:10)

breaks_x <- scales::breaks_extended()(range(df$x))

df %>% 
  plot_ly() %>% 
  add_markers(x = ~x,
              y = ~y) %>% 
  layout(xaxis = list(
    ticktext = paste0(breaks_x, ifelse(breaks_x >= 0, "%", "")), 
    tickvals = breaks_x,
    tickmode = "array"
  ))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading