Home > Software design >  Different axis label format depending on value using plotly
Different axis label format depending on value using plotly

Time:11-23

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?

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

CodePudding user response:

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"
  ))

  • Related