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
Doug Fir
  • 19,971
  • 47
  • 169
  • 299
  • Possible duplicate https://stackoverflow.com/questions/9531904/plot-multiple-columns-on-the-same-graph-in-r and https://stackoverflow.com/questions/4877357/how-to-plot-all-the-columns-of-a-data-frame-in-r – Ronak Shah Dec 16 '20 at 01:37

2 Answers2

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

akrun
  • 874,273
  • 37
  • 540
  • 662
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

Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29