2

I'm trying to create the following plot in ggplot that I generated from example data in R using the plot function.

volt1 <- seq(from=-200, to=200, by =5)
current <- seq(from=-200, to=200, by =5)

value <- c()
for (i in 1:length(current)){
  if (current[i] < 0){
    value[i] <- -(current[i]^2)
  }
  else{
    value[i] <- current[i]^2
  }
}
}

df1 <- data.frame(volt, value)

plot(df, axes = FALSE)
axis(1, pos=0)
axis(2, pos=0)

Intial R Plot

I'm having issues creating this in ggplot. First, it doesn't seem like you can alter the position of the axes beyond "top", "bottom", "left", or "right". I've gotten around this by using the geom_vline() and geom_hline(), but now the issues is being able to re-create the tick marks on each respective axes (see code output below).

p <-ggplot(data = df1,aes(x = volt, y = value)) +
  geom_point(size = 4) +
  theme_classic() +
  scale_x_continuous(position = "top") +
  theme(axis.line.x = element_blank()) +
  geom_hline(yintercept = 0) +
  scale_y_continuous(position = "right") +
  theme(axis.line.y = element_blank()) +
  geom_vline(xintercept = 0)


p

GGplot Produced example

duckmayr
  • 16,303
  • 3
  • 35
  • 53
  • Just a remark: your way of computing `value` is untypical for R and also (for large amounts of data) very inefficient. There is no need to write a for-loop and you can simply write: `value <- sign(current) * current^2`. This works because taking the power with `^` and `sign()` both operate element-wise. – Stibu Mar 21 '20 at 16:09

0 Answers0