Reputation: 21292
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.
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
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 ) )
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 )
Upvotes: 1
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()
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"))
Upvotes: 3