'ggplot within function does not fully work

I am trying to create Bland-Altman plots between 2 sets of percentages with a custom function that uses ggplot within it to generate the plot.

Perc1 <- sample(1:100, 100)
Perc2 <- sample(1:100, 100)
d <- data.frame(Perc1, Perc2)

bland <- function(dat, x, y){
  df <- subset(dat[ ,c(x, y)])
  df$avg <- rowMeans(df)
  df$diff <- df[[1]] - df[[2]]
  mean_diff <- mean(df$diff)
  lower <- mean_diff - 1.96 * sd(df$diff)
  upper <- mean_diff + 1.96 * sd(df$diff)
  p <- ggplot(df, aes(x = avg, y = diff)) +
    geom_point(size=2) +
    geom_hline(yintercept = mean_diff) +
    geom_hline(yintercept = lower, color = "red", linetype="dashed") +
    geom_hline(yintercept = upper, color = "red", linetype="dashed") +
    ggtitle("Bland-Altman Plot") +
    ylab("Difference Between Measurements") +
    xlab("Average Measurement")
  plot(p)
}

bland(d, Perc1, Perc2)

However, when I run the function none of the lines are produced with the graph, but the title and x/y labels are. If anyone can explain why this is that would be great, thanks in advance.



Solution 1:[1]

Try this:

(Note also, the p <- and plot(p) are not needed as the function anyway returns the last object.)

library(tidyverse)

Perc1 <- sample(1:100, 100)
Perc2 <- sample(1:100, 100)

bland <- function(x, y){
  df <- data.frame(x, y)
  df$avg <- rowMeans(df)
  df$diff <- df[[1]] - df[[2]]
  mean_diff <- mean(df$diff)
  lower <- mean_diff - 1.96 * sd(df$diff)
  upper <- mean_diff + 1.96 * sd(df$diff)
  p <- ggplot(df, aes(x = avg, y = diff)) +
    geom_point(size=2) +
    geom_hline(yintercept = mean_diff) +
    geom_hline(yintercept = lower, color = "red", linetype="dashed") +
    geom_hline(yintercept = upper, color = "red", linetype="dashed") +
    ggtitle("Bland-Altman Plot") +
    ylab("Difference Between Measurements") +
    xlab("Average Measurement")
  plot(p)
}

bland(Perc1, Perc2)

Created on 2022-05-17 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1