Doug Fir
Doug Fir

Reputation: 21292

Plot multiple columns on same plot

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

Upvotes: 0

Views: 4100

Answers (2)

Andre Wildberg
Andre Wildberg

Reputation: 19191

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

Upvotes: 1

akrun
akrun

Reputation: 887781

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

Upvotes: 3

Related Questions