0

This is a really basic question but I can't find a similar one, so I'm asking here. I want to create multiple ggplots (xy-charts specifically) using the same x and a different y, all from the same data frame (using the values in one column for x and each of the other columns for a y).

My first approach would have been to use a for loop to cycle through the table, but inputting a string (as would result from, say, colnames(mtcars[i])):

ggplot(data=mtcars,aes(x=mpg,y="cyl"))

is interpreted completely differently from

ggplot(data=mtcars,aes(x=mpg,y=cyl))

What would be the correct approach to this (other than copying, pasting and replacing the input of y every time, of course)?

vladbadu
  • 1
  • 1
  • If your `y` values have the same units, the simple approach would be to reshape longer (e.g. `tidyr::pivot_longer(Y_COLS)` and then use `facet_wrap` in ggplot2 to map those to different facets. – Jon Spring Jul 18 '22 at 18:35
  • 1
    (1) Your code is incomplete, you are missing both a close-paren and something to show (e.g., `geom_point()`). (2) `aes(y="cyl")` is mapping `y` to the literal string `"cyl"`, not to the column with the data `mtcars`. If you want to control aesthetics programmatically, read the [quasiquotation section of `aes`](https://ggplot2.tidyverse.org/reference/aes.html#quasiquotation). – r2evans Jul 18 '22 at 18:37
  • While @r2evans is absolutely right that quasiquotation is a thing to know about in these kind of circumstances, it's also quite a deep topic that is difficult to understand. For a quick and dirty solution check out [aes_string](https://ggplot2.tidyverse.org/reference/aes_.html) – SamR Jul 18 '22 at 18:42
  • @r2evans sorry for the parentheses. I didn't add +geom_point() because it wasn't all that essential to the question. Thanks for the link, in any case – vladbadu Jul 18 '22 at 18:48
  • @ SamR and Limey thanks for the suggestions, will look it up – vladbadu Jul 18 '22 at 18:50

0 Answers0