【问题标题】:Plot two matrices into one with ggplot使用 ggplot 将两个矩阵合二为一
【发布时间】:2020-08-22 02:14:21
【问题描述】:

我使用 matplot() 将 2 个矩阵绘制成一张图,但我没有得到 ggplot 等效项。 以下是矩阵:

矩阵 A:足球比赛中的得分尝试

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

矩阵 B:游戏数

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

以下代码完美运行

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)

ggplot 等效项似乎有些不对劲。帮我把这个也弄好,谢谢!

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)

【问题讨论】:

    标签: r ggplot2 matrix


    【解决方案1】:

    首先,由于缺少+ 符号,您的labs()geom_line() 未连接到ggplot()

    尝试复制您的代码如下

    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)
    

    创建这个

    假设上图是正确的,你需要一些额外的数据通过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)
    

    得到这个

    现在你只需要微调所有的缩放来得到你想要的。

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多