Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading