rmbaughman
rmbaughman

Reputation: 921

Plotly zerolines at different levels on double axis plot

I'm trying to overlay a line chart and bar chart in plotly (with a vertical line designating an important date) and I'm encountering this issue where the two zero lines are offset instead of on the same line. I've tried messing around with the overlaying = 'y' option within layout and tried changing the order of the three trace components but nothing seems to help. Any ideas how to fix? Below is my code with dummy data:

(Also, bonus points if you can fix my legend-overlapping-y2axis issue)

date <- seq(as.Date("2015/6/1"), by = "month", length.out = 19) 
wires_mnth <- c(rep(0,8),100000,750000,1200000,2500000,3100000,5500000,7500000,8000000,9900000,11300000,11000000)
wires_cnt <- c(rep(0,8),100,200,250,325,475,600,750,800,1000,1150,1200)
data <- data.frame(date, wires_mnth)

plot_ly(data) %>%
add_trace(x = ~date, y = ~wires_cnt, type = 'bar', name = 'Wires Count', 
    yaxis = 'y2', opacity = .5) %>%
add_trace(x = ~date, y = ~wires_mnth, type = 'scatter', mode = 'lines', name 
    = 'Monthly Wires') %>%
add_trace(x = c(2016,2016), y = c(0, 12000000), type = 'scatter', mode = 
    "lines", name = 'Sanctions Removed') %>%

layout(title = 'Monthly Aggregate Wire Transfers to Iran',
     xaxis = list(title = ''),
     yaxis = list(side = 'left', title = 'Wire Amounts (USD)', showgrid = 
         FALSE, zeroline = FALSE),
     yaxis2 = list(side = 'right', overlaying = 'y', title = 'Wires Count', 
        showgrid = FALSE, zeroline = FALSE)
     )

enter image description here

Upvotes: 5

Views: 2409

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31739

You could add rangemode='nonnegative' to your layout or specify the range manually via range=list(0, max(wires_mnth).

For your bonus question, you can set the x-position of the legend, e.g. legend = list(x = 1.2)

enter image description here

Upvotes: 5

Related Questions