Tom
Tom

Reputation: 43

How to use a variable as an argument of ggplot?

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]])

Upvotes: 1

Views: 907

Answers (2)

Thomas Bilach
Thomas Bilach

Reputation: 591

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.

Upvotes: 1

akrun
akrun

Reputation: 886938

We can convert to symbol and evaluate (!!

...
    p = ggplot(Dat, aes(x=!! rlang::sym(x), y=y))+
...

Upvotes: 2

Related Questions