user3833612
user3833612

Reputation: 427

R- shiny-plotly second axis label overlapped with yaxis values

I am using R, shiny and plotly trying to build an interactive user interface. Basically, I have a dataset dest which has two columns Date and price. Here is a basic line plot:

ay <- list(
showticklabels = TRUE,
overlaying = "y",
side = "right",
title = "Benchmark price")

p<-plot_ly(dset, x = ~Date,y= ~Price,type = 'scatter',mode ='lines',marker=list(size = 10),name=paste0(input$select_bench," as of ",input$benchdate)) %>% layout(xaxis = ax, yaxis2 =ay)

p<-add_trace(p,x=~bDate,y=~bPrice,type = 'scatter',mode = 'lines',marker=list(size = 10),name=paste0(input$select_bench," as of ",input$benchdate),textposition = 'middle right',yaxis="y2")}

layout(p,legend = list(orientation = 'h'),title = 'Commodity Price Trending')

I am using the

legend = list(orientation = 'h')

here since I want to put the legend at the bottom. However if I do this, the second axis value on the right is overlapped with the label and is only showing part of the number, for example it is showing 5 instead of 59.

I think there should be a parameter to adjust the default margin of the display area - but tried hard googling not found anything.

Upvotes: 3

Views: 3414

Answers (1)

vpz
vpz

Reputation: 1044

You could use automargin = T in yaxis2.

Try this:

# Dummy data

set.seed(123)

dset = data.frame(Date = seq.Date(from = as.Date("2016-07-05"),to = as.Date("2020-01-05"), by = "month"),
                  Price = c(57,59.5,rnorm(n = 41, mean = 58.75, sd = .1))
                  )

# layout of yaxis2
ay <- list( showticklabels = TRUE,
            overlaying = "y",
            side = "right",
            title = "Benchmark price",
            automargin = T # This do the trick
            )

# Example of your plot
dset %>%
  plot_ly(x = ~Date,y= ~Price,type = 'scatter',mode ='marker+lines',marker=list(size = 10), name = "A") %>%
  add_trace(x = ~Date, y = ~Price , name = "B", yaxis = "y2") %>%
  layout(legend = list(orientation = 'h'),
         title = 'Commodity Price Trending',
         yaxis2 = ay
         )

Here the ouput plot: plot

Upvotes: 7

Related Questions