Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding second Y axis on ggplotly

I have created the following dataframe object and graph using plotly and ggplot

library(ggplot2)
library(plotly)

rdate <- function(x,
              min = paste0(format(Sys.Date(), '%Y'), '-01-01'),
              max = paste0(format(Sys.Date(), '%Y'), '-12-31'),
              sort = TRUE) {          
  dates <- sample(seq(as.Date(min), as.Date(max), by = "day"), x, replace=TRUE)
  if (sort == TRUE) {
    sort(dates)
  } else {
    dates
  }
}

DF<-data.frame(Date = rdate(100))
DF$variable<-LETTERS[seq( from = 1, to = 10 )]
DF$Value<-round(runif(1:nrow(DF),min = 10, max = 50))

Next I have created a plot object with ggplot

 p <- ggplot(DF, aes(x = Date, y = Value, colour = variable)) + 
  geom_line() + 
  ylab(label="Sellcount") + 
  xlab("Sell Week")
  p<-p + scale_y_continuous(sec.axis = dup_axis())
  ggplotly(p)

IF i plot p using plot(p), the graph has 2 yaxes as I expect. However, when I use ggplotly(p) to plot the graph, only one Y axis is generated. I am unable to find any literature on the internet regarding the same. I request someone to help me in this.

like image 584
Raghavan vmvs Avatar asked Oct 16 '18 10:10

Raghavan vmvs


1 Answers

A simple workaround is to add the second axis manually:

ay <- list(
  tickfont = list(size=11.7),
  titlefont=list(size=14.6),
  overlaying = "y",
  nticks = 5,
  side = "right",
  title = "Second y axis"
)

ggplotly(p) %>%
  add_lines(x=~Date, y=~Value, colors=NULL, yaxis="y2", 
            data=DF, showlegend=FALSE, inherit=FALSE) %>%
  layout(yaxis2 = ay)

enter image description here

like image 120
Marco Sandri Avatar answered Oct 14 '22 23:10

Marco Sandri