1

Let's consider the following example.

Dat is a data frame with variables y, a, b, and c.

I would like to create three scatter plots where y is on the y axis and a, b, or c is on the x axis.

I used a for loop as follows.

I know x = x in aes(x = x, y = y) is wrong. My question is how to modify x = x to make it work.

library(ggplot2)

x_vec = c("a", "b", "c")

a = 1:10
b = a+10
c = b+10
y = 1:10

Dat = data.frame(y = y, a = a, b = b, c = c)
str(Dat)

p_list = list()

for (i in 1:3) {
    # i = 1
    x = x_vec[i]
    x
    p = ggplot(Dat, aes(x = x, y = y)) +
        geom_point()
    p_list[[i]] = p
}

plot(p_list[[1]])
plot(p_list[[2]])
plot(p_list[[3]])
1
  • This is programming rather than statistics Commented May 17, 2021 at 16:36

2 Answers 2

2

We can convert to symbol and evaluate (!!

...
    p = ggplot(Dat, aes(x=!! rlang::sym(x), y=y))+
...
Sign up to request clarification or add additional context in comments.

Comments

1

Why not take advantage of ggplot's functionality?

Once your data is in long format it's easier to create small multiples across each category. This answer assumes you want three separate scatterplots. Try this out:

library(ggplot2)
library(dplyr)

a = 1:10
b = a + 10
c = b + 10
y = 1:10

dat <- data.frame(y = y, a = a, b = b, c = c)

dat_long <- dat %>%
  pivot_longer(cols = `a`:`c`, names_to = "labels", values_to = "x") %>%
  arrange(labels)

ggplot(dat_long, aes(x = x, y = y)) +
  geom_point() +
  theme_minimal() +
  facet_wrap(~ labels)

small multiples

If you must execute this using a for loop, then see the accompanying answer.

1 Comment

Thanks. Your alternative solution is better than mine with a for loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.