Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gist demonstrating an R error
# The question: why does make.plot.1 cause an error?
# make.plot.2 and make.plot.3 work ok.
#
# I'm trying to use ggplot to make a scatter plot with
# with size mapped to the "s" variable in the dataframe.
# When I try to draw circles on top of the scatter plot using geom_path, I get
# errors.
# The plot works if I choose to not map size or not to draw the circles.
library(ggplot2)
make.circle <- function(d) {
alpha <- seq(0.0, 360.0, 0.1) / 180 * pi
data.frame(x = d*cos(alpha), y = d*sin(alpha))
}
# Calling this function results in an error
make.plot.1 <- function(df) {
p <- ggplot(df, aes(x, y, size = s)) + geom_point() +
geom_hline(yintercept = 0) +
geom_vline(xintercept = 0) +
geom_path(aes(x, y), data = make.circle(0.5)) +
geom_path(aes(x, y), data = make.circle(1)) +
geom_path(aes(x, y), data = make.circle(1.5)) +
geom_path(aes(x, y), data = make.circle(2))
print(p)
return(p)
}
# Calling this function works fine.
make.plot.2 <- function(df) {
p <- ggplot(df, aes(x, y)) + geom_point() +
geom_hline(yintercept = 0) +
geom_vline(xintercept = 0) +
geom_path(aes(x, y), data = make.circle(0.5)) +
geom_path(aes(x, y), data = make.circle(1)) +
geom_path(aes(x, y), data = make.circle(1.5)) +
geom_path(aes(x, y), data = make.circle(2))
print(p)
return(p)
}
# This function also works
make.plot.3 <- function(df) {
p <- ggplot(df, aes(x, y, size = s)) + geom_point() +
geom_hline(yintercept = 0) +
geom_vline(xintercept = 0)
print(p)
return(p)
}
data <- data.frame(x = rnorm(100), y = rnorm(100), s = rnorm(100))
# This results in an error
# make.plot.1(data)
# This works:
make.plot.2(data)
# This works:
make.plot.3(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment