【问题标题】:Converting matrix into scatterplot将矩阵转换为散点图
【发布时间】:2014-08-04 19:46:49
【问题描述】:

我有一个看起来像这样的矩阵:

      1 2 3 4 5 6 7 8 9
name1 0 0 1 0 1 0 0 0 0
name2 1 1 0 0 0 0 0 0 0
name3 0 0 0 2 0 0 0 0 0
name4 0 1 0 0 0 0 0 1 0

我想制作一种散点图,即当有“1”时为红点,当有“2”时为绿点,当为“0”时没有任何内容。 Name* 是行名。我怎样才能做到这一点? 我想替换热图。

【问题讨论】:

    标签: r matrix plot


    【解决方案1】:

    这将进行绘图:

    plot(which(d==1, arr.ind=TRUE)[,'col'], which(d==1,arr.ind=TRUE)[,'row'], col="red", 
        xlim=c(1,ncol(d)), ylim=rev(c(1,nrow(d))))
    points(which(d==2, arr.ind=TRUE)[,'col'], which(d==2,arr.ind=TRUE)[,'row'], col="green")
    

    如果您不喜欢默认行为,可以显式设置行号和列号:

    plot(which(d==1,arr.ind=TRUE)[,'col'], which(d==1,arr.ind=TRUE)[,'row'], col="red", 
        xlim=c(1,ncol(d)), ylim=rev(c(1,nrow(d))), xaxt="n", yaxt="n")
    points(which(d==2,arr.ind=TRUE)[,'col'], which(d==2,arr.ind=TRUE)[,'row'], col="green")
    axis(1, at = seq(1, 9, by = 1))
    axis(2, at = seq(1, 4, by = 1))
    

    【讨论】:

      【解决方案2】:

      这是一个 ggplot2 解决方案。

      x = "0 0 1 0 1 0 0 0 0
           1 1 0 0 0 0 0 0 0
           0 0 0 2 0 0 0 0 0
           0 1 0 0 0 0 0 1 0"
      
      df = (t(matrix(scan(text= x), nrow = 9)))
      library(reshape2)
      df = melt(d[c(4:1),])
      
      ggplot(df[df$value!=0,], aes(y = X1, x = X2)) +
        geom_point(aes(col = factor(value)), size = 10) +
        scale_color_manual(name="", values = c("red", "green")) +
        scale_y_continuous(label = paste(rep("name", 4), 1:4)) +
        scale_x_continuous(breaks = 1:8) +
        theme_bw() + xlab("") + ylab("")
      

      【讨论】:

      • 如果我在 y 轴上有很多变量“名称”怎么办?如果我使用 scale_y_continuous 我会收到错误“中断和标签的长度不同”,但是当我使用 scale_y_discrete 时,并非所有“名称”都会显示在图上。
      • 您需要将这里的两个4s paste(rep("name", 4), 1:4)) 更改为您拥有的实际姓名数。而且由于弗兰克提到y标签是翻转的。改为这样做rev(paste(rep("name", n), 1:n)))
      猜你喜欢
      • 2021-02-28
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2015-09-17
      • 2020-07-01
      相关资源
      最近更新 更多