0

I'm using geom_smooth to fit in a regression line like below. It does a bit more than line fit. It also adds a table of sample count to the ggplot chart.

sctrFn = function(df, colNameX, colNameY) {
 
  dfPlot = df %>%
    select(!!colNameX, !!colNameY)
  
  # scatter plot with line fit
  p = ggplot(dfPlot, aes_string(x=colNameX, y=colNameY)) + 
    geom_point() +
    geom_smooth(method=loess, se=T, fullrange=F, size=1)
  # p = p + ylim(0,5)
  
  # sample count table
  tb = df %>%
    filter(!is.na(!!as.name(colNameX)) & !is.na(!!as.name(colNameY))) %>%
    do(data.frame(Count=nrow(.)))
  
  # create plot data
  data.plot = tibble(x = 0, y = 0, p = list(p))
  data.tb = tibble(x = 1, y = 0.05, tbl = list(tb))
  
  # scatter plot with table
  return (
    ggplot() + xlim(c(0,1)) + ylim(c(0,1))  + theme_void() +
      geom_plot(data = data.plot, aes(x, y, label = p,vp.width = 0.95,vp.height = 0.95)) +
      geom_table(data = data.tb, aes(x,y,label = tbl,hjust=1,vjust=1))
  )
  
}

This gives me a chart like below which is perfect.

enter image description here

However, I want to get a closeup of this chart by limiting the y-axis from 0 to 5 - this would be something like the below, but with smaller intervals of 1 unit in y-axis tick marks. I tried adding p = p + ylim(0,5) in the above function. However, this completely changes the regression line and doesn't give the expected outcome.

enter image description here

user3206440
  • 4,749
  • 15
  • 75
  • 132
  • 2
    Similar https://stackoverflow.com/questions/26225670/zoom-in-ggplot-after-creating-reviewing – polkas Sep 27 '20 at 06:45
  • 1
    ... or https://stackoverflow.com/questions/8235844/geom-smooth-and-scaling-the-y-axis-losing-data-from-smoothing – stefan Sep 27 '20 at 07:27

0 Answers0