Gaga
Gaga

Reputation: 101

Plot two matrices into one with ggplot

I plotted 2 matrices into one graph with matplot(), I am not getting the ggplot equivalent right. Here are the matrices:

Matrix A : Score attempt in a football match

       John   Mike   Luc
2010    20    30      25
2011    13    22      18
2012    10    20      14

Matrix B : Number of Games

       John   Mike   Luc
2010    10    15      12
2011     5     8       7
2012     2     8       3

The following code works perfectly

a <- Score_Attempts
b <- Num_Of_Games
matplot(a, b, type = "l", xlab = "Score attempt", ylab = "Number of game")
legend("bottomright", legend = colnames(a), col = seq_len(a),  pch = 1, cex = 0.7)

Something seems not right with the ggplot equivalent. Assist me getting this one right too, Thanks!

data <- data.frame(ScoreAttempt = as.vector(a),
                     NumOfGame = as.vector(b))

ggplot(data, mapping = aes(x = ScoreAttempt, y = NumOfGame ))
  labs(x="Score attempt", y= "Number of game") +
  geom_line(size = 2)

Upvotes: 0

Views: 1209

Answers (1)

statstew
statstew

Reputation: 311

First off, your labs() and geom_line() are not connected to the ggplot() due to a missing + sign.

Tried to replicate your code as follows

a <- matrix( c(20,30,25,13,22,18,10,20,14), ncol=3, byrow=TRUE )
dimnames(a) <- list( 2010:2012, c("John","Mike","Luc") )

b <- matrix( c(10,15,12,5,8,7,2,8,3), ncol=3, byrow=TRUE )
dimnames(b) <- list( 2010:2012, c("John","Mike","Luc") )

matplot(a, b, type = "l", xlab = "Score attempt", ylab = "Number of game")
legend("bottomright", legend = colnames(a), col = seq_len(a),  pch = 1, cex = 0.7)

to create this

enter image description here

Assuming the above picture is correct, you need to some additional data to recreate it via ggplot2

data <- data.frame( Individual=rep(c("John","Mike","Luc"),each=3),
                    Year=rep(2010:2012,3),
                    ScoreAttempt = as.vector(a),
                    NumOfGame = as.vector(b) )

ggplot(data, mapping = aes(x = ScoreAttempt, y = NumOfGame, color=Individual, group=Individual ) ) +
  labs(x="Score attempt", y= "Number of game") +
  geom_line(size = 2)

to get this

enter image description here

Now you just need to fine tune all of the scaling to get what you want.

Upvotes: 1

Related Questions