0
mydf <- data.frame(
  id = 1:12,
  x = rnorm(12),
  y = rnorm(12),
  z = rnorm(12)
)

# base r
plot(mydf$x)
plot(mydf$y)
plot(mydf$z)

One of these looks like e.g.

enter image description here

what is the equivilent, if any in ggplot and can I display all 3 on one plot using color to separate them? Perhaps using a line?

mydf %>% ggplot(aes(x)) + geom_point()
Error: geom_point requires the following missing aesthetics: y
1

2 Answers 2

3

We can reshape to 'long' format with pivot_longer and plot at once

library(dplyr)
library(tidyr)
library(ggplot2)
mydf %>%
     mutate(rn = row_number()) %>% 
     pivot_longer(cols = -rn) %>%
     ggplot(aes(x = rn, y = value, color = name)) + 
          geom_point()

It may be also better to have geom_line as it will show the trend more easily

mydf %>%
  mutate(rn = row_number()) %>% 
  pivot_longer(cols = -rn) %>%
  ggplot(aes(x = rn, y = value, color = name)) + 
       geom_line()

enter image description here


Or using base R with matplot

matplot(as.matrix(mydf), type = 'l', col = c('red', 'green', 'blue'))
legend("topright", legend = names(mydf), fill = c('red', "green", "blue"))

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

Using base R (and ggplot2):

require(ggplot2)

mydd <- setNames( data.frame( matrix( rep(c("x","y","z"), each=12) ),
 c(mydf$x, mydf$y, mydf$z) ), c("x_point","data")) # convert to long format

ggplot( mydd ) + geom_line( aes( rep(1:12, 3), data, col=x_point ) )

ggplot2

only base R:

plot(mydf$x, t="l", col="red", ylim=c(min(mydf[,2:4]),max(mydf[,2:4])))
lines(mydf$y, col="green")
lines(mydf$z, col="blue")
legend( "bottomleft", legend=c("x","y","z"), col=c("red","green","blue"), lwd=1 )

enter image description here

Comments

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.