2

Good time! I have the following code and I need to draw many parallel lines in the loop (the loop is where the word "dice"). I need to draw 6 times, but as the result only one appeared. Could anyone help me? Thank you.

library(ggplot2)

plot_constraints <- function() {
  x <- seq(-5, 25, by = 0.1)
  f1 <- (141000 - 4000*x) / 5000
  f2 <- 17
  f3 <- 19
  obj.func <- (-3*x/5)
  
  df <- data.frame(x, f1)
  
  p <- ggplot(df, aes(x = x))
  
  dice <- c(1, 2, 3, 4, 5, 6)
  for (x in dice) {
    p <- p + geom_line(aes(y = obj.func + x), color = "grey", lwd=0.5)
  }
  
  p <- p + geom_line(aes(y = f1), color = "red", lwd=1.4) +
    geom_vline(xintercept = f3, color = "green", lwd=1.4) +
    geom_hline(yintercept = f2, color = "blue", lwd=1.4) +
    geom_vline(xintercept = 0, color = "black", lwd=1.4) +
    geom_hline(yintercept = 0, color = "black", lwd=1.4) +
    coord_cartesian(xlim = c(0, 20), ylim = c(0, 20)) +
    labs(x = "Three-tonne trucks", y = "Five-tonne trucks") +
    theme_classic()
  p
}
plot_constraints()
Beef Fat
  • 23
  • 4
  • Yeah, I changed.. But there is still only 1 line. But I need to draw 6 parallel lines according to my loop. – Beef Fat Apr 10 '23 at 09:06
  • hey, try embracing `{{ x }}` or prefixing it with `!!` where you want to pass it to `aes()` (tidy evaluation). Does this help you? https://stackoverflow.com/questions/4856849/looping-over-variables-in-ggplot – uke Apr 10 '23 at 09:12

1 Answers1

3

Using the !! ("bang bang") operator solves the problem. Here is the changed line:

dice <- c(1:6)
  for (x in dice) {

## changes are here
    p <- p + geom_line(aes(y = !!obj.func + !!x), color = "grey", lwd=0.5)

  }

Here is the output of plot_constraints():

plot

uke
  • 462
  • 1
  • 11