Different y axis when knitting

In RStudio preview I get a plot:

Yet, when knitting I get a different y axis:

What might I be doing wrong here?

Code:

ticker = "SPY"

options = getOptionChain( ticker ) #, NULL)

calls = as_tibble(options$calls)
puts = as_tibble(options$puts)

options = 
  merge(calls, puts, by="Strike", suffixes = c(".calls", ".puts"), all=TRUE, sort=TRUE ) %>%
  #
  mutate( OI.puts  = replace_na(OI.puts,0) ) %>%
  mutate( OI.calls = replace_na(OI.calls,0) ) %>%
  #
  mutate( TotalCallsOi = cumsum(OI.calls) ) %>%
  #
  arrange(desc(Strike)) %>%
  mutate( TotalPutsOi = cumsum(OI.puts) ) %>%
  #
  arrange(Strike) %>%
  select(Strike, OI.calls, OI.puts, TotalPutsOi, TotalCallsOi) 
  
 
optionsLonger =
  options %>%
  select(Strike, OI.calls, OI.puts) %>%
  rename("Calls"="OI.calls", "Puts"="OI.puts") %>%
  pivot_longer(!c(Strike), names_to = "type", values_to = "OI")

xMin = 400
xMax = 475 
axis2Coeff = 10
colorCalls = "green"
colorPuts  = "red"


ggplot(data=optionsLonger) +
  geom_bar(stat="identity", position="dodge", width=0.5, aes(x=Strike, y=OI, fill=type)) +
  scale_fill_manual( values=c(colorCalls, colorPuts) ) +
  geom_line( data=options, aes(x=Strike, y=TotalPutsOi/axis2Coeff),  size=0, color=colorPuts) +
  geom_line( data=options, aes(x=Strike, y=TotalCallsOi/axis2Coeff), size=0, color=colorCalls) +
  scale_y_continuous(
    #trans='log2'
    sec.axis = sec_axis( trans=~.*axis2Coeff, name="Cummulative Open Interest" )
    ) +
  scale_x_continuous( breaks = seq(xMin, xMax, 10), lim=c(xMin, xMax) ) +
  #xlim(xMin, xMax) +
  #
  theme_tq() +
  labs(
    title = paste0(ticker, " options (current)"  ),
    subtitle = "",  
    x = "Strike Price",
    y = "Open Interest",
    fill = "",
    caption = ""  
  ) +
  annotate("text", x = xMin+1, y = 45000, size=3, colour = "burlywood3", hjust="left", vjust="top", 
           label = "Ian Worthington\nData from Yahoo Finance")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.