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.
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.